6 条题解
-
17
拿走不谢
#include <iostream> #include <cmath> using namespace std; int n, a[15],cnt; void dfs(int sum,int x) { if (sum == 0) { if(cnt==1) return; for (int i = 1; i < cnt; i++) cout << a[i] << "+"; cout << a[cnt] << endl; return; } for (int i = x; i <= sum; i++) { cnt++; a[cnt] = i; dfs(sum-i,i); cnt--; } } int main() { cin >> n; cnt=0; dfs(n,1); return 0; }
-
6
思路
考虑dfs(sum)表示需要对sum进行拆分成若干数的和,使用数组a储存拆分结果,cnt储存数组a的长度。 但又由于要求要字典序顺序输出,所以需要保证每次后面的加数比前面的加数大,所以可以给dfs函数增加一个维度x,记录上一个加数。 $\\$初始时,由于需要拆分的数时n,第一个加数最小是1,所以dfs(n,1); $\\$dfs函数中,当sum为0时说明不需要继续拆分了,直接输出结果,注意最后输出的数不需要加号,需要特殊处理。 $\\$否则,下一个加数i可以从x到sum,将a数组长度++,并且记录为i,继续dfs(sum-i,i);之后记得回溯,cnt--。代码
#include <iostream> #include <cmath> using namespace std; int n, a[15],cnt; void dfs(int sum,int x) { if (sum == 0) { if(cnt==1) return; for (int i = 1; i < cnt; i++) cout << a[i] << "+"; cout << a[cnt] << endl; return; } for (int i = x; i <= sum; i++) { cnt++; a[cnt] = i; dfs(sum-i,i); cnt--; } } int main() { cin >> n; cnt=0; dfs(n,1); return 0; }
-
2
这道题的关键在于记录上一个加数并保证比它大 然后便采用这节课所学知识解题,注意回溯便OK
#include <bits/stdc++.h> using namespace std; int n,sum,x; int a[10]; void dfs(int x,int before) { if (sum == n) { for (int i = 1;i <= n;i++) { if (a[i]) { cout << a[i]; if (a[i+1] == 0) { break; } cout << "+"; } } cout << endl; return; } for (int i = 1;i < n;i++) { if (sum + i <= n && i >= before) { sum += i; a[x] = i; dfs(x+1,i); a[x] = 0; sum -= i; } } } int main() { cin >> n; dfs(1,0); return 0; }//已AC,别忘点赞
呃,代码有些头重脚轻,改成这样或许会好一点
#include <bits/stdc++.h> using namespace std; int n,sum,x; int a[10]; void dfs(int x,int before); int main() { cin >> n; dfs(1,0); return 0; } void dfs(int x,int before) { if (sum == n) { for (int i = 1;i <= n;i++) { if (a[i]) { cout << a[i]; if (a[i+1] == 0) { break; } cout << "+"; } } cout << endl; return; } for (int i = 1;i < n;i++) { if (sum + i <= n && i >= before) { sum += i; a[x] = i; dfs(x+1,i); a[x] = 0; sum -= i; } } }
大家觉得呢?
-
0
#include <iostream> #include <cmath> using namespace std; int n, a[15],cnt; void dfs(int sum,int x) { if (sum == 0) { if(cnt==1) return; for (int i = 1; i < cnt; i++) cout << a[i] << "+"; cout << a[cnt] << endl; return; } for (int i = x; i <= sum; i++) { cnt++; a[cnt] = i; dfs(sum-i,i); cnt--; } } int main() { cin >> n; cnt=0; dfs(n,1); return 0; }
已AC😄 😄 😄
-
0
#include <iostream> #include <cmath> using namespace std; int n, a[15],cnt; void dfs(int sum,int x) { if (sum == 0) { if(cnt==1) return; for (int i = 1; i < cnt; i++) cout << a[i] << "+"; cout << a[cnt] << endl; return; } for (int i = x; i <= sum; i++) { cnt++; a[cnt] = i; dfs(sum-i,i); cnt--; } } int main() { cin >> n; cnt=0; dfs(n,1); return 0; }
- 1
信息
- ID
- 331
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 1
- 标签
- (无)
- 递交数
- 434
- 已通过
- 320
- 上传者