# 組合問題 ## C#, 組合問題, 若陣列有4個items, 想取出二個items為一組, 請問有多少種組合, 並列出它們 陣列有4個items,取出2個items為一組的組合問題是一個典型的「組合」問題。根據組合公式,C(n, k) = n! / (k! * (n - k)! ),其中n為總數量,k為選擇的數量,n!表示n的階乘。 在這個情況下,我們有n = 4個items,想要選擇k = 2個items為一組。計算組合數量: C(4, 2) = 4! / (2! * (4 - 2)!) = 24 / (2 * 2) = 6 所以有6種組合。假設陣列為[a, b, c, d],則這6種組合分別為: (a, b) (a, c) (a, d) (b, c) (b, d) (c, d) ## 如何使用C#程式列出所有組合 要使用C#程式列出所有組合,您可以使用遞迴函數或迭代方法。以下是使用迭代方法的一個範例: ``` using System; using System.Collections.Generic; class Program { static void Main() { char[] items = { 'a', 'b', 'c', 'd' }; int k = 2; List<char[]> combinations = GetCombinations(items, k); foreach (char[] combination in combinations) { Console.WriteLine(string.Join(", ", combination)); } } static List<char[]> GetCombinations(char[] items, int k) { List<char[]> result = new List<char[]>(); int n = items.Length; if (k > n) return result; int[] indices = new int[k]; for (int i = 0; i < k; i++) { indices[i] = i; } while (true) { char[] currentCombination = new char[k]; for (int i = 0; i < k; i++) { currentCombination[i] = items[indices[i]]; } result.Add(currentCombination); int indexToIncrement = k - 1; while (indexToIncrement >= 0 && indices[indexToIncrement] == n - k + indexToIncrement) { indexToIncrement--; } if (indexToIncrement < 0) break; indices[indexToIncrement]++; for (int i = indexToIncrement + 1; i < k; i++) { indices[i] = indices[i - 1] + 1; } } return result; } } ``` 這個程式首先定義了一個GetCombinations函數,該函數接受一個字符陣列items和一個整數k,並返回一個字符陣列列表,其中每個元素是一個包含k個字符的陣列。主函數則調用GetCombinations並輸出結果。