點部落首po~~遞迴求組合問題

  • 652
  • 0

點部落首po~~遞迴求組合問題

這是我第一次使用點部落,感覺還滿好玩的!!!

晚上剛好看到有人在ptt在詢問,也看到許多高手回覆答案,一時手癢...然後又剛好看到有人使用點部落,就來嘗鮮一下吧^^

題目是:有 N 堆(依使用者輸入),每一堆裡面放不同種類的東西 (種類數不定值),然後要列出所有的組合。

N 堆的題目就先寫死(也是參考網友的題目),結果放在一個ListBox內。

如果有錯誤歡迎指正阿~!!!!

   1: using System;
   2: using System.Collections.Generic;
   3: using System.ComponentModel;
   4: using System.Data;
   5: using System.Drawing;
   6: using System.Linq;
   7: using System.Text;
   8: using System.Windows.Forms;
   9: using System.Windows.Media;
  10:  
  11: namespace WindowsFormsApplication1
  12: {
  13:     public partial class Form1 : Form
  14:     {
  15:         List<List<string>> _questionGroupList = new List<List<string>>();
  16:  
  17:         public Form1()
  18:         {
  19:             InitializeComponent();
  20:             List<string> AGroup = new List<string>();
  21:             AGroup.Add("A");
  22:             AGroup.Add("B");
  23:             AGroup.Add("C");
  24:             _questionGroupList.Add(AGroup);
  25:             List<string> BGroup = new List<string>();
  26:             BGroup.Add("D");
  27:             BGroup.Add("Z");
  28:             _questionGroupList.Add(BGroup);
  29:             List<string> CGroup = new List<string>();
  30:             CGroup.Add("E");
  31:             CGroup.Add("F");
  32:             _questionGroupList.Add(CGroup);
  33:             List<string> DGroup = new List<string>();
  34:             DGroup.Add("G");
  35:             DGroup.Add("K");
  36:             _questionGroupList.Add(DGroup);
  37:             Run();
  38:         }
  39:  
  40:         public void Run()
  41:         {
  42:             ResultLbx.Items.Clear();
  43:             GetValue(0, "");
  44:  
  45:         }
  46:  
  47:         public void GetValue(int groupIndex, string result)
  48:         {
  49:             if (_questionGroupList.Count > groupIndex)
  50:             {
  51:                 for (int i = 0; i < _questionGroupList[groupIndex].Count; i++)
  52:                 {
  53:                     string childResult = null;
  54:                     if (!String.IsNullOrEmpty(result))
  55:                         childResult = result + ", " + _questionGroupList[groupIndex][i];
  56:                     else
  57:                         childResult = _questionGroupList[groupIndex][i];
  58:                     if (groupIndex + 1 < _questionGroupList.Count)
  59:                     {
  60:                         GetValue(groupIndex + 1, childResult);
  61:                     }
  62:                     else
  63:                     {
  64:                         ResultLbx.Items.Add(childResult);
  65:                     }
  66:                 }
  67:             }
  68:         }
  69:     }
  70: }