递归法求解数列组合的各种情况
C#代码:
static void Main(string[] args)
{
int[] items = new int[] { 0,1,2,3,4};
int m = 3;
List<int[]> allCombinations = GetCombinations(items, m);
foreach (int[] combination in allCombinations)
{
Console.WriteLine(string.Join(",", combination));
}
}
static List<int[]> GetCombinations(int[] items, int m)
{
List<int[]> allCombinations = new List<int[]>();
int[] combination = new int[m];
GetCombinations(items, m, 0, combination, 0, allCombinations);
return allCombinations;
}
static void GetCombinations(int[] items, int m, int itemIndex, int[] combination, int combinationIndex, List<int[]> allCombinations)
{
if (combinationIndex == m)
{
allCombinations.Add((int[])combination.Clone());
return;
}
if (itemIndex >= items.Length)
{
return;
}
combination[combinationIndex] = items[itemIndex];
GetCombinations(items, m, itemIndex + 1, combination, combinationIndex + 1, allCombinations);
GetCombinations(items, m, itemIndex + 1, combination, combinationIndex, allCombinations);
}
图解:
#####
愿你一寸一寸地攻城略地,一点一点地焕然一新
#####