Files
python/GESP/Mkx/20250401T6.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

44 lines
1.1 KiB
C++
Raw 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, m;
vector<int> vec;
/*
输入:
13 3
答案:
1 2 10
1 3 9
1 4 8
1 5 7
2 3 8
2 4 7
2 5 6
3 4 6
*/
void dfs(int x, int c) {
// 注意下面的两层判断!!!
if (x == 0) { // 这是递归出口
if (c == m) { // 不是所有到达递归出口的方案都是可行的,只有到达递归出口并且,数量等于m的方案才是可行的
for (int i = 0; i < vec.size(); i++)
cout << vec[i] << " ";
cout << endl;
}
// 这个return是配合递归出口设置的,不管方案是不是可行,都要结束递归。
return;
}
// 当前位置可以放下每个小于等于x的数字
for (int i = !vec.size() ? 1 : vec.back() + 1; i <= x; i++) { // 三元表达式:如果vec.size()为0,则i=1,否则i=vec.back()+1
vec.push_back(i); // 回溯法
dfs(x - i, c + 1); // 数字在减少,个数在增加,vec是大黑板,c是小纸条
vec.pop_back();
}
}
int main() {
cin >> n >> m;
dfs(n, 0);
return 0;
}