时间限制: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
思路:深度搜索
代码:
//DFS
#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;
int num[11],n,r;
void dfs(int x,int y)
{
if(y==0)
{
for(int i=r; i>0; i--)
printf("%d",num[i]);
printf("\n");
}
else
{
for(int i=x; i>=y; i--)
{
num[y]=i;
dfs(i-1,y-1);//y-1代表数组的位置
}
}
}
int main()
{
while(~scanf("%d%d",&n,&r))
{
dfs(n,r);
}
return 0;
}