【发布时间】:2009-12-29 15:29:50
【问题描述】:
我正在编写一个程序来尝试解决数学问题。我需要生成一个所有数字的唯一列表,这些数字加起来是另一个数字。例如,所有 4 个数字加起来为 5 的唯一组合是:
5 0 0 0
4 1 0 0
3 2 0 0
3 1 1 0
2 2 1 0
2 1 1 1
这在 perl 中很容易暴力破解,但我正在使用 C 语言并希望找到更优雅的解决方案。
在 perl 中,我会在每列中生成数字 0-N 的所有可能组合,丢弃不加起来等于目标数字的数字,然后对每行中的数字进行排序并删除重复的行。
我整个上午都在尝试用 C 语言编写它,但似乎无法找到令人满意的解决方案。我需要它达到最大 N 约为 25。你们有什么想法吗?
这是我一直在尝试的一种示例(这会产生重复的组合):
// target is the number each row should sum to.
// Don't worry about overflows, I am only using small values for target
void example(int target)
{
int row[4];
for (int a=target; a>=0; a--) {
row[0] = a;
for (int b=target-a; b>=0; b--) {
row[1] = b;
for (int c=target-(a+b); c>=0; c--) {
row[2] = c;
row[3] = target-(a+b+c);
printf ("%2d %2d %2d %2d sum: %d\n", row[0],row[1],row[2],row[3],
row[0]+row[1]+row[2]+row[3]);
}
}
}
}
【问题讨论】:
-
例子真的清楚吗?为什么
2 2 1 0组合没有列出来? -
糟糕,我错过了一个示例组合,刚刚添加了它。
-
你的数字有多大?最简单的解决方案可能是递归解决方案,但对于较大的数字,这可能会让您陷入本网站命名的那种问题。
-
不大于约target = 25,列数固定为4