打印数字N的所有组合,作为正整数的总和? [英] Print all combinations of a number N, as a sum of positive integers?

查看:69
本文介绍了打印数字N的所有组合,作为正整数的总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:


3 =

2 1

1 2

1 1 1


4 =

3 1

1 3

1 1 2

1 2 1

2 1 1

1 1 1 1


依旧...



如何在C中编写一个程序来解决这个问题...我甚至无法弄清楚算法?

For example:

3=
2 1
1 2
1 1 1

4=
3 1
1 3
1 1 2
1 2 1
2 1 1
1 1 1 1

and so on...


How to write a program in C for such a problem...I can''t even seem to figure out the algo?

推荐答案

@vikrantt


一些想法:

-每个数字c更少比n,c +(n - c)= n

-如上所述,你可以递归地做到这一点。例如,如果2 + 3 = 5,则总和为2的数字加上总和为3的数字也为5.

- 您只需要计算从(n / 2)到n的数字的总和;在下面,总和是相同的,只是相反。即

4 + 2 = 6

3 + 3 = 6

2 + 4 = 6< - 你可以在3 + 3停止


希望这有帮助。
@vikrantt
Some thoughts:
-for every number c less than n, c + (n - c) = n
-given the above, you can do this recursively. For instance, if 2 + 3 = 5 then the numbers summing to 2 plus the numbers summing to 3 also = 5.
-you only have to calculate sums for numbers from (n/2) through n; below that the sums are the same, just reversed. i.e.
4 + 2 = 6
3 + 3 = 6
2 + 4 = 6 <- you can stop at 3 + 3

Hope this helps.


好吧,我想我没说清楚。但我不需要计算数字,而是打印它们。这里1 2,不同于2 1.或者我们可以跳过排列。
okay, i think i did not make it clear. But I do not need to calculate the numbers, rather print them. And here 1 2, is different than 2 1. Or may be we can skip permutation.


@vikrantt


我不清楚你需要什么,那么。

你是否已经有算法计算数字,或者数字是否已预先计算好?这是您可以担心打印它们之前的第一步。

如果您已经完成了第一步,那么您是否仍然坚持如何将数字输出到屏幕上?
@vikrantt
I''m not clear on what you need, then.
Do you already have an algorithm to compute the numbers, or are the numbers precomputed? That would be the first step before you can worry about printing them.
If you''ve already got the first step down, are you stuck on how to output the numbers to the screen?


这篇关于打印数字N的所有组合,作为正整数的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆