我正在尝试编写一种算法,以从一组数字中选择n个值的所有组合。
例如,给定集合:1, 2, 3, 7, 8, 9
集合中2个值的所有组合为:
3是:
等等!
我目前正在使用方法来产生2、3和4值的组合的返回集,但在我看来,这可以在LINQ查询中推广。
谢谢你的帮助!
最佳答案
用法:
var results = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }.DifferentCombinations(3);
代码:
public static class Ex
{
public static IEnumerable<IEnumerable<T>> DifferentCombinations<T>(this IEnumerable<T> elements, int k)
{
return k == 0 ? new[] { new T[0] } :
elements.SelectMany((e, i) =>
elements.Skip(i + 1).DifferentCombinations(k - 1).Select(c => (new[] {e}).Concat(c)));
}
}