利用深度优先搜索的性质可以方便的生成n的排列和组合。生成排列(默认是全排列,也可以传个参数生成n的k排列)
#include<cstdio>
#define MAXN 111
using namespace std;
int tmp[MAXN],vis[MAXN],n,k;
void dfs(int cnt,int num = n){
if(num > n){
printf("the input data is invalid !!!\n");
return;
}
if(cnt == num){
for(int i = 0;i < cnt;i ++) printf("%d ",tmp[i]);
printf("\n");
}
for(int i = 1;i <= n;i ++){
if(!vis[i]){
vis[i] = 1;
tmp[cnt] = i;
dfs(cnt+1,num);
vis[i] = 0;
}
}
}
int main(){
while(~scanf("%d%d",&n,&k)) dfs(0,k);
return 0;
}
#include<cstdio>
#define MAXN 111
using namespace std;
int tmp[MAXN],n,k;
void dfs(int idx,int cnt,int k){
if(k > n){
printf("the input data is invalid!!!\n");
return;
}
if(cnt == k){
for(int i = 0;i < cnt;i ++) printf("%d ",tmp[i]);
printf("\n");
}
for(int i = idx;i <= n;i ++){
tmp[cnt] = i;
dfs(i+1,cnt+1,k);
}
}
int main(){
while(~scanf("%d%d",&n,&k)) dfs(1,0,k);
return 0;
}