题目
从 这 个整数中随机选出 个,输出所有可能的选择方案。
输入格式
两个整数 ,在同一行用空格隔开。
输出格式
按照从小到大的顺序输出所有方案,每行 个。
首先,同一行内的数升序排列,相邻两个数用一个空格隔开。
其次,对于两个不同的行,对应下标的数一一比较,字典序较小的排在前面(例如 1 3 5 7
排在 1 3 6 8
前面)。
数据范围
,
,
输入样例:
5 3
输出样例:
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
思考题:如果要求使用非递归方法,该怎么做呢?
题解
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 <iostream> #include <algorithm> #include <vector>
using namespace std;
const int N = 100;
int n, m; int vec[N];
void dfs(int u, int x) { if (u > m) { for (int i = 1; i <= m; ++ i) cout << vec[i] << " "; cout << endl; return; }
for (int i = x; i <= n; ++ i) { vec[u] = i; dfs(u + 1, i + 1); } }
int main() { cin >> n >> m; dfs(1, 1); return 0; }
|