与全排列问题唯一不同点是,本题的输出有递增要求;
#include <bits/stdc++.h>
using namespace std;
const int N = 25;
int n,k;
int path[N];
void dfs(int step,int x){
if(step == k)
{
for(int i = 0; i < k; i++){
cout << setw(3) << path[i];
}
cout << endl; //换行
return;
}
//剪枝
//当剩下的数不够填的时候不用再搜索了
if(n - x < k - step) return;
//x + 1 满足元素的递增关系
for(int i = x + 1; i <= n; i++){
path[step] = i;
dfs(step + 1, i);
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> k;
dfs(0,0);
return 0;
}