组合数
时间限制:3000 ms | 内存限制:65535 KB
难度:3
描述
找出从自然数1、2、… 、n(0 < n < 10)中任取r(0 < r<=n)个数的所有组合。
输入输入n、r。输出按特定顺序输出所有组合。
特定顺序:每一个组合中的值从大到小排列,组合之间按逆字典序排列。
样例输入
5 3
样例输出
543
542
541
532
531
521
432
431
421
321
虽然是以前做过的一道简单的搜索题目,但是再次回来做一遍,发现自己好像更
加明白了一点,温故而知新吧
//从后向前,搜索满足条件的结果
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
int n,r;
int ans[12];
void dfs(int c,int t)//c是当前遍历到的位置,t+1是当前元素的下标
{
if(t==r)//满足条件,输出
{
for(int i=1;i<r;i++)
printf("%d",ans[i]);
printf("%d\n",ans[r]);
return ;
}
for(int i=c;i>0;i--)
{
ans[t+1]=i;
dfs(i-1,t+1);//注意这里是i-1,而不是c-1
}
}
int main()
{
while(scanf("%d %d",&n,&r)!=EOF)
{
dfs(n,0);
}
return 0;
}