一、【问题描述】
7-1 前t个组合结果 (25分)
组合结果
找出从自然数1、2、… 、n(0<n<=30)中任取r(0<r<=n)个数的组合,输出其中前t个组合结果。
输入格式:
在一行中输入n、r、t(1<=t<=C(n,r))。
输出格式:
按特定顺序输出前t个组合结果,每一个组合结果占一行,含第一个整数在内的每一个整数前面都用一个空格,最后一个整数后面没有空格。 特定顺序:每一个组合结果中的值从大到小排列,组合之间按逆字典序排列。
输入样例:
在这里给出一组输入。例如:
5 3 10
6 4 8
输出样例:
在这里给出相应的输出。例如:
5 4 3
5 4 2
5 4 1
5 3 2
5 3 1
5 2 1
4 3 2
4 3 1
4 2 1
3 2 1
6 5 4 3
6 5 4 2
6 5 4 1
6 5 3 2
6 5 3 1
6 5 2 1
6 4 3 2
6 4 3 1
二、【题解】
深度优先搜索(DFS)
#include<iostream>
using namespace std;
int a[30],book[30],n,r,t,m;//book[]为标记数组
void dfs(int n,int count,int r){
if(m==t)return;//为了保证是前t个组合
if(count>r)return;//返回最近一次调用dfs函数的地方
for(int i=n;i>=1;i--){//从n开始是为了组合结果能够从大到小排列
if(book[i]==0){
a[count]=i;
book[i]=1;
if(count==r){
m++;//产生的满足条件的组合+1
for(int i=1;i<=r;i++)
printf(" %d",a[i]);
printf("\n");
}
dfs(i,count+1,r);//函数递归调用
book[i]=0;//取消标记
}
}
}
int main(){
while(cin>>n>>r>>t){
m=0;
dfs(n,1,r);
}
return 0;
}