考点
题解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| #include <bits/stdc++.h> using namespace std; const int LEN = 8; int N, ans[LEN];
void dfs(int cnt, int pre, int sum) { if (sum > N) return; if (sum == N && cnt > 1) { cout << ans[0]; for (int i = 1; i < cnt; ++i) cout << "+" << ans[i]; cout << endl; return; } for (int i = pre; i <= N; ++i) { ans[cnt] = i; dfs(cnt + 1, i, sum + i); } }
int main() { cin >> N; dfs(0, 1, 0); return 0; }
|
思路
标准的dfs模板题,没有坑点;唯一注意的是,需要额外增加一个pre
变量保存上一次递归选择的数
因为根据题意,后面的数应该大于等于前面的数