18712 递归实现组合
时间限制:1000MS 代码长度限制:10KB
提交次数:0 通过次数:0
题型: 编程题 语言: 不限定
Description
找出从自然数1、2、……、m中任取k个数的所有组合,组合中字典序大的先输出。
例如m=5,k=3,应输出
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
输入格式
两个整数m和k,(1<=k<=m<=10)
输出格式
按字典序输出所有组合
输入样例
5 2
输出样例
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
本题的思路是利用递归,dfs的方法来找到所有满足条件的组合数即可。
分为两种输出,正序输出和逆序输出,当时逆序输出利用book数组来求解花费了很长时间,会输出两次,原因是将前一个数解除绑定的时候会重新再输出一次,再返回上一次dfs,导致产生了两组一模一样的答案,以下是AC代码
倒序输出
#include <iostream>
using namespace std;
const int M=15;
int n,m,ans[M];
void dfs(int step,int val)
{
if(step==m+1)
{
for(int i=1;i<=m;i++)
{
cout<<ans[i]<<' ';
}
cout<<'\n';
return ;
}
for(int j=val;j>=1;j--)
{
ans[step]=j;
dfs(step+1,j-1);
}
return ;
}
int main()
{
ios::sync_with_stdio(false);
cin>>n>>m;
dfs(1,n);
return 0;
}
正序输出
#include <iostream>
using namespace std;
const int M=15;
int n,m,ans[M];
void dfs(int step,int val)
{
if(step==m+1)
{
for(int i=1;i<=m;i++)
{
cout<<ans[i]<<' ';
}
cout<<'\n';
return ;
}
for(int j=val;j<=n;j++)
{
ans[step]=j;
dfs(step+1,j+1);
}
return ;
}
int main()
{
ios::sync_with_stdio(false);
cin>>n>>m;
dfs(1,1);
return 0;
}