Files
python/TangDou/LuoGuBook/P2404.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

49 lines
1.2 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
//哪个数字
int n;
//全局路径(需要回溯)
vector<int> path;
//输出
void print() {
//划分成两部分,最后一部分不在尾巴上加+号!
for (int i = 0; i < path.size() - 1; i++) cout << path[i] << "+";
cout << path[path.size() - 1] << endl;
}
//深度优先搜索
void dfs(int x, int sum) {
//终止条件
if (path.size() > 1 && n == sum) {//需要把一个数字描述成2个及2个以上数字的和
// 自已描述自己不行就是path.size()>1
print();
return;
}
//本轮添加上什么样的数字可以是123...,n
for (int i = 1; i <= x; i++) {
//1、路径空的时候可以放
//2、路径不空同时当前要加入的数字比尾巴上的数字要大也可以放
if (path.empty() || i >= path[path.size() - 1]) {
//加入
path.push_back(i);
//递归
dfs(x - i, sum + i);
//回溯
path.pop_back();
}
}
}
int main() {
//输入
cin >> n;
//深度优先搜索
dfs(n, 0);
return 0;
}