题目链接
Description
任何一个大于1的自然数n,总可以拆分成若干个小于n的自然数之和。现在给你一个自然数n,要求你求出n的拆分成一些数字的和。每个拆分后的序列中的数字从小到大排序。然后你需要输出这些序列,其中字典序小的序列需要优先输出。
Input
第一行为一个正整数n。
Output
若干数的加法式子。
Sample Input 1
7
Sample Output 1
1+1+1+1+1+1+1
1+1+1+1+1+2
1+1+1+1+3
1+1+1+2+2
1+1+1+4
1+1+2+3
1+1+5
1+2+2+2
1+2+4
1+3+3
1+6
2+2+3
2+5
3+4
Hint
1≤n≤8
题解思路:我们利用n,保存当前n所剩没有加过的值,然后对当前所剩数进行搜索,top表示可拆分的个数。
心得:在写递归或搜索代码时,要尽量减少传递参数,以降低编程难度和提高代码效率。可以动态及时更新的值,都应该尽量定义成全局变量。
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef pair<int, int> PII;
const int N = 110;
int n,top;
int line[N];
void dfs(int last)
{
if (n == 0) {
if (top == 1) return;
cout << line[1];
for (int i = 2;i <= top;i ++ ) cout << '+' << line[i];
puts("");
}
for (int i = last;i <= n;i ++ ) {//为了保证从小到大遍历
line[++ top] = i;
n -= i;
dfs(i);
top --;//回溯
n += i;
}
}
int main()
{
cin >> n;
dfs(1);
return 0;
}