【发布时间】:2026-01-23 10:15:02
【问题描述】:
假设我有一个任意长度的整数列表,例如我有 1、3、5 和 7 的列表。
我想要一个算法来从列表中选择 X 元素的组合。
例如,X = 1 会返回:
1
3
5
7
x = 2 将返回:
1 + 1
1 + 3
1 + 5
1 + 7
3 + 3
3 + 5
3 + 7
5 + 5
5 + 7
7 + 7
var listOfInts = new List<int> { 1, 3, 5, 7 };
var combinedInts = new List<int>();
// x = 1 solution
// This is only picking one item from the list.
for (int i = 0; i < listOfInts.Count(); i++)
{
combinedInts.Add(listOfInts[i]);
}
// x = 2 solution
// This is how to pick two. I wrap it around another for loop.
for (int i = 0; i < listOfInts.Count(); i++)
{
for (int j = i; j < listOfInts.Count(); j++)
{
combinedInts.Add(listOfInts[i] + listOfInts[j]);
}
}
// x = 3 solution
// If I go up another level I have to wrap it around another for loop. This solution won't scale.
for (int i = 0; i < listOfInts.Count(); i++)
{
for (int j = i; j < listOfInts.Count(); j++)
{
for (int k = j; k < listOfInts.Count(); k++)
{
combinedInts.Add(listOfInts[i] + listOfInts[j] + listOfInts[k]);
}
}
}
此解决方案无法扩展,因为我必须为我选择的每个元素数量不断地环绕另一个 for 循环。例如 X = 7 需要 7 个嵌套的 for 循环。有没有更好的方法来编写这个不涉及嵌套 for 循环的方法?
【问题讨论】:
-
您希望递归地调用单个循环的函数。递归示例见dotnetperls.com/recursion
-
这实际上应该是 *.com/questions/4073713/… 的副本 - 您正在寻找 x 个列表的笛卡尔积。要获得总和,您只需将其汇总即可。
-
@Rob 你是对的 - 我选错了一个(在你发表评论时重新打开:))。请注意,“选择一个不同的数字”可能意味着 combinations of k items from n,但 sample 确实谈到了笛卡尔积。
-
@Layoric,递归的例子,实际见here
-
我不相信建议的副本回答了这个问题。首先,在问题的示例中,一旦选择了一个元素,只有从该点开始的元素用于组合(即不是真正的笛卡尔积)。其次,OP 专门要求聚合任意多个序列,因此存在一个简单的笛卡尔积没有解决的递归元素(即使这是一个真正的笛卡尔积)。