值列表的所有可能组合

我的C#程序中有一个整数列表。但是,我只在运行时知道列表中的项目数。

让我们说,为了简单起见,我的列表是{1,2,3}现在我需要生成所有可能的组合,如下所示。{1,2,3} {1,2} {1,3} {2,3} {1} {2} {3}

有人可以帮忙吗?


胡说叔叔
浏览 380回答 3
3回答

紫衣仙女

以下是强类型列表的两个通用解决方案,它们将返回列表成员的所有唯一组合(如果您可以使用更简单的代码解决此问题,我向您致敬):// Recursivepublic static List<List<T>> GetAllCombos<T>(List<T> list){&nbsp; List<List<T>> result = new List<List<T>>();&nbsp; // head&nbsp; result.Add(new List<T>());&nbsp; result.Last().Add(list[0]);&nbsp; if (list.Count == 1)&nbsp; &nbsp; return result;&nbsp; // tail&nbsp; List<List<T>> tailCombos = GetAllCombos(list.Skip(1).ToList());&nbsp; tailCombos.ForEach(combo =>&nbsp; {&nbsp; &nbsp; result.Add(new List<T>(combo));&nbsp; &nbsp; combo.Add(list[0]);&nbsp; &nbsp; result.Add(new List<T>(combo));&nbsp; });&nbsp; return result;}// Iterative, using 'i' as bitmask to choose each combo memberspublic static List<List<T>> GetAllCombos<T>(List<T> list){&nbsp; int comboCount = (int) Math.Pow(2, list.Count) - 1;&nbsp; List<List<T>> result = new List<List<T>>();&nbsp; for (int i = 1; i < comboCount + 1; i++)&nbsp; {&nbsp; &nbsp; // make each combo here&nbsp; &nbsp; result.Add(new List<T>());&nbsp; &nbsp; for (int j = 0; j < list.Count; j++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; if ((i >> j) % 2 != 0)&nbsp; &nbsp; &nbsp; &nbsp; result.Last().Add(list[j]);&nbsp; &nbsp; }&nbsp; }&nbsp; return result;}// Example usageList<List<int>> combos = GetAllCombos(new int[] { 1, 2, 3 }.ToList());

富国沪深

这是使用递归的通用解决方案public static ICollection<ICollection<T>> Permutations<T>(ICollection<T> list) {&nbsp; &nbsp; var result = new List<ICollection<T>>();&nbsp; &nbsp; if (list.Count == 1) { // If only one possible permutation&nbsp; &nbsp; &nbsp; &nbsp; result.Add(list); // Add it and return it&nbsp; &nbsp; &nbsp; &nbsp; return result;&nbsp; &nbsp; }&nbsp; &nbsp; foreach (var element in list) { // For each element in that list&nbsp; &nbsp; &nbsp; &nbsp; var remainingList = new List<T>(list);&nbsp; &nbsp; &nbsp; &nbsp; remainingList.Remove(element); // Get a list containing everything except of chosen element&nbsp; &nbsp; &nbsp; &nbsp; foreach (var permutation in Permutations<T>(remainingList)) { // Get all possible sub-permutations&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; permutation.Add(element); // Add that element&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.Add(permutation);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return result;}我知道这是一篇旧帖子,但有人可能会觉得这很有帮助。
打开App,查看更多内容
随时随地看视频慕课网APP