我的解决方案使用简单的递归算法来创建组合:
我假设元素不应重复(即 { 1, 1 } 或 { 1, 2, 1 } 是不允许的)。如果您想允许重复元素,您可以删除 remaining 变量并在对 GetCombinations 的递归调用中将其替换为 values。
请注意yield 关键字的使用。这意味着代码使用延迟执行。在实际枚举结果之前无需存储任何中间结果。
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