与排序型枚举相比,多传入了一个参数,为了保证枚举出来的顺序是从小到大的
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 30;
int n,m;
int way[N];
void dfs(int u, int start)
{
//剪枝,加快速度
//(u-1) + (n-start +1) < m
//如果把后面所有数都选上,都不够m个,当前分支就一定不无解
if (u + n - start < m) {s
return;
}
if (u == m + 1) {
for (int i = 1; i <= m; i++) {
printf("%d ", way[i]);
}
puts("");
return;
}
for (int i = start; i <= n; i++) {
way[u] = i;
dfs(u + 1, i + 1);
way[u] = 0; //恢复现场
}
}
int main()
{
scanf("%d %d", &n, &m);
dfs(1, 1);
return 0;
}