使用三个数字查找整数的总数组合

对于给定的整数n ,我需要打印长度为3的所有列表,它们总和为n 。 列表的成员必须是非负整数。 打印完所有这些列表后,必须打印找到的列表数。

例如,如果n = 2

  • 1 + 0 + 1 = 2
  • 1 + 1 + 0 = 2
  • 0 + 1 + 1 = 2
  • 2 + 0 + 0 = 2
  • 0 + 0 + 2 = 2
  • 0 + 2 + 0 = 2

这是我为长度为2的列表而不是长度为3的列表所做的程序:

#include  int main (void) { int total; int c1=0; int c2=0; int c3=0; int count; printf("Welcome friends and mainly enemies to the thingy. Only postive intergers!!!\n That's right just enter a number here:"); scanf ("%d",&total); printf ("\n\n\nWhy pick %d? Here is the list if combinations anyway,",total); for (count=0;count<=total;count++) { printf ("\n"); for (c1=count;c1==count;c1--) { printf("%d ",c1); } for (c2=total-count;c2<=total-count;c2++) { printf("%d",c2); } } printf ("\n\nThere are %d number combinations that total %d",count,total); } 

目标是将其从长度为2的列表扩展到长度为3的列表。

附加信息:我只能使用另一个变量c3。

希望这可以帮助:

 int c3 = 0; for (int c1 = 0; c1 <= total; c1++) { for (int c2 = total - c1; c2 >= 0; c2--){ printf("%d %d %d \n", c1, c2, total - c1 - c2); c3++; } } printf("there are %d ways to sum to %d", c3, total); 

如果你只对这个数字感兴趣,那么答案就是重复总数+ 1元素第二课:让我解释一下:让我们考虑1的total 。 它们在计算第一个1之前和最后一个之后的间隙之间total + 1间隙。 您正在尝试选择总计达到总数的3个数字:我们将通过在我刚才解释的空白处放置分隔符来实现。 第一个数字将是第一个分隔符之前的数字之和,第二个数字是分隔符之间的数字,第三个数字是剩余的数字。 请注意,因为我们允许数字为零,所以我们允许将分隔符放在相同的间隙中,也可以放在第一个1之前和最后一个之后。这完全等同于“重复总共+ 1个元素的组合”第2课“正如我已经说过的那样,是经典的组合问题。 你可以在这里阅读这些组合,但基本上答案是((总+ 1)*(总+ 2))/ 2.顺便说一下,我建议用至少算法标签来解决这个问题。

编辑 :按照进一步解释的要求,我将用例子说明我的所有想法(实际上是你在问题中给出的同一个例子):我们需要分成三组中的两个。 2引导我们看到我们要编写的数量:_1_1_。 在这里,我用’_’写下了所谓的“我”。 现在,我将用’|’表示两个分隔符。 同样,分隔符用于确定在sum分区中第一个,第二个和第三个数字的1s数量。 在左边,我使用我的符号来编写组合,在右边用符号表示相应的组合。

 ||_1_1_ -> 0, 0, 2 |_1|_1_ -> 0, 1, 1 |_1_1|_ -> 0, 2, 0 _1||_1_ -> 1, 0, 1 _1|_1|_ -> 1, 1, 0 _1_1||_ -> 2, 0, 0 

现在,希望您更好地理解什么是分隔符以及如何使用它们来确定组合中使用的三个数字是什么。 如果增加total逻辑保持不变,但如果需要说明案例,则需要编写更多。

可能现在你也理解为什么差距total + 1以及两个分离器中的每一个如何恰好出现在这两个间隙中。 所有这一切导致我们承诺与重复第二类的total + 1元素的组合。

 #include  void main() { unsigned int num, p1, p2, p3, count=0; printf("Enter a positive number : "); scanf("%d", &num); for (p1=0; p1<=num; p1++) { for (p2=0; p2<=num; p2++) { for (p3=0; p3<=num; p3++) { if (p1 + p2 + p3 == num) { count++; printf("%d + %d + %d = %d\n", p1, p2, p3, num); } } } } printf("\nThe total combinations for your number %d = %d", num, count); } 

在我看来,这是数学不编程的问题

如果所有三个整数都是不同的,可以使用一次以上:

 3 possibilities for 1st digit 3 possibilities for 2nd digit 3 possibilities for 3rd digit -- 27 = 3*3*3