我的解决方案使用简单的递归算法来创建组合:
我假设元素不应重复(即不允许使用 { 1, 1 } 或 { 1, 2, 1 } )。如果你想允许重复的元素,你可以删除remaining
变量并将其替换为values
在递归调用中GetCombinations
.
请注意使用yield http://msdn.microsoft.com/library/9k7k7cf0.aspx关键词。这意味着代码使用了延迟执行。在实际枚举结果之前无需存储任何中间结果。
public static IEnumerable<IEnumerable<T>> GetCombinations<T>(IEnumerable<T> values, int threshold)
{
var remaining = values;
foreach (T value in values)
{
yield return value.Yield();
if (threshold < 2)
{
continue;
}
remaining = remaining.Skip(1);
foreach (var combination in GetCombinations(remaining, threshold - 1))
{
yield return value.Yield().Concat(combination);
}
}
}
public static IEnumerable<T> Yield<T>(this T item)
{
yield return item;
}
对于整数数组 { 1, 2, 3, 4, 5 } 输出为:
1
1, 2
1, 2, 3
1, 2, 4
1, 2, 5
1, 3
1, 3, 4
1, 3, 5
1, 4
1, 4, 5
1, 5
2
2, 3
2, 3, 4
2, 3, 5
2, 4
2, 4, 5
2, 5
3
3, 4
3, 4, 5
3, 5
4
4, 5
5