打印整数划分
时间限制:3000 ms | 内存限制:65535 KB
难度:3
- 描述
- 将正整数n表示成一系列正整数之和:n=n1+n2+…+nk,
其中n1≥n2≥…≥nk≥1,k≥1。
正整数n的这种表示称为正整数n的划分。求正整数n的不
同划分个数。
例如正整数6有如下11种不同的划分:
6;
5+1;
4+2,4+1+1;
3+3,3+2+1,3+1+1+1;
2+2+2,2+2+1+1,2+1+1+1+1;
1+1+1+1+1+1。
- 输入
- 第一行是测试数据的数目M(1<=M<=10)。以下每行均包含一个整数n(1<=n<=10)。
- 输出
- 输出每组测试的划分,格式如上所示。
- 样例输入
-
1 6
- 样例输出
- 6
5+1
4+2,4+1+1
3+3,3+2+1,3+1+1+1
2+2+2,2+2+1+1,2+1+1+1+1
1+1+1+1+1+1
1 // 打印整数划分 2 #include <cstdio> 3 #include <iostream> 4 5 using namespace std; 6 int cnt, tot; 7 int a[100]; 8 9 void fun(int n, int sum) 10 { 11 if(sum == tot) //注意这里的打印技巧 12 { 13 for(int i = 0; i < cnt-1; ++i) 14 printf("%d+", a[i]); 15 if(tot - a[0] == cnt-1) 16 printf("%d\n", a[cnt-1]); 17 else 18 printf("%d,", a[cnt-1]); 19 return; 20 } 21 for(int i = n; i > 0; --i) 22 { 23 if(sum + i <= tot) 24 { 25 a[cnt++] = i; 26 fun(i, sum+i);//注意这里不是fun (n - i, sum+i),因为每次的划分结果都是从大到小排序的 27 //所以每次枚举的最大数不能大于上一次的值; 28 cnt--; // 记得这里要回溯 29 } 30 } 31 } 32 33 int main() 34 { 35 int T; 36 scanf("%d", &T); 37 while(T--) 38 { 39 cnt= 0; 40 scanf("%d", &tot); 41 fun(tot, 0); 42 } 43 return 0; 44 }