问题 B: 【递归入门】组合的输出
时间限制: 1 Sec 内存限制: 128 MB
提交: 128 解决: 70
题目描述
排列与组合是常用的数学方法,其中组合就是从n个元素中抽出r个元素(不分顺序且r < = n),我们可以简单地将n个元素理解为自然数1,2,…,n,从中任取r个数。
现要求你不用递归的方法输出所有组合。
例如n = 5 ,r = 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
输入
一行两个自然数n、r ( 1 < n < 21,1 < = r < = n )。
输出
所有的组合,每一个组合占一行且其中的元素按由小到大的顺序排列,所有的组合也按字典顺序。
经验总结
写递归程序,还是要把思路理清,理清思路,就好写了( •̀∀•́ )
非递归代码
#include <cstdio>
#include <stack>
#include <vector>
using namespace std;
int n,r;
void combine()
{
stack<int> process;
vector<int> answer;
process.push(1);
answer.push_back(1);
int elem;
bool pop=false;
while(!process.empty())
{
if(answer.size()==r)
{
for(int i=0;i<r;i++)
{
printf("%d ",answer[i]);
}
printf("\n");
pop=true;
}
elem=process.top();
if(elem==n)
{
process.pop();
answer.pop_back();
pop=true;
continue;
}
if(pop)
{
process.pop();
answer.pop_back();
pop=false;
}
if(elem<n)
{
process.push(elem+1);
answer.push_back(elem+1);
}
}
}
int main()
{
while(~scanf("%d %d",&n,&r))
{
combine();
}
return 0;
}
递归代码
#include <cstdio>
using namespace std;
int n,r;
int ans[26];
bool flag[26]={false};
void combine(int x,int count)
{
if(count==r)
{
for(int i=0;i<r;i++)
{
printf("%d ",ans[i]);
}
printf("\n");
return;
}
for(int i=x;i<=n;i++)
{
if(flag[i-1]==false)
{
ans[count]=i;
flag[i-1]=true;
combine(i,count+1);
flag[i-1]=false;
}
}
}
int main()
{
while(~scanf("%d %d",&n,&r))
{
combine(1,0);
}
return 0;
}