#include<iostream>#include<vector>int n, m;
std::vector<int>res;bool st[30];voidPrint(){for(int i=0;i<res.size();i++){printf("%d ",res[i]);}puts("");}voiddfs(int num){if(res.size()== m){Print();return;}for(int i = num;i<= n; i++){if(!st[i]){st[i]=true;res.push_back(i);if(res.size()==1&& res[0]>(n-m+1)){res.pop_back();st[i]=false;continue;}dfs(i +1);st[i]=false;res.pop_back();}}}intmain(void){scanf("%d %d",&n,&m);dfs(1);return0;}
解法二
#include<iostream>#include<vector>int n, m;
std::vector<int>res;bool st[30];voiddfs(int start){if(res.size()==m){for(int i=0;i<res.size();i++){printf("%d ",res[i]);}puts("");return;}for(int i=start;i<=n;i++){res.push_back(i);dfs(i+1);res.pop_back();}}intmain(void){scanf("%d %d",&n,&m);dfs(1);return0;}