我希望能获得一个包含重复元素的所有可能组合的列表。
例如:
Input: 1,2,3
Result: 111,112,...,332,333
我使用这个修改过的方法来完成,目前它运行得很好。
public static IEnumerable<IEnumerable<T>> CombinationsWithRepeat<T>(this IEnumerable<T> elements, int k)
{
return k == 0 ? new[] { new T[0] } : elements.SelectMany((e, i) => elements.CombinationsWithRepeat(k - 1).Select(c => (new[] { e }).Concat(c)));
}
我的问题是这个递归方法的内存使用情况。当输入为60个元素且K = 4时,已经出现了
内存不足异常
。我需要以K = 10运行此程序。
问题:有没有简单的方法可以避免这个异常?我需要采用迭代方法吗?
更新:
根据Corak的评论 - K必须是动态的。
这应该可以处理60个元素和
K = 10
,但它不是动态的。StreamWriter sr = new StreamWriter(@"c:\temp.dat");
List<char> cList = new List<char>() { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
for (int i = 0; i < cList.Count; i++)
for (int j = 0; j < cList.Count; j++)
for (int k = 0; k < cList.Count; k++)
sr.WriteLine(cList[i] + cList[j] + cList[k]);
K
也可以是不同的数字 - 那部分必须是动态的。 - fuboK
值创建方法,然后使用适合的方法。再次强调:虽然不太美观,但是可行的。 - Corak