描述找出从自然数1、2、... 、n(0<n<10)中任取r(0<r<=n)个数的所有组合。
-
输入
- 输入n、r。 输出
-
按特定顺序输出所有组合。
特定顺序:每一个组合中的值从大到小排列,组合之间按逆字典序排列。
样例输入
-
5 3
样例输出
-
543 542 541 532 531 521 432 431 421
321
-
备注
-
解法一中传参为a-1与--a时情况不同...有点玄学。
-
典型深搜题,用for循环遍历符合要求范围内的数字,进入下一层时搜索范围减1。
-
#include <iostream> using namespace std; int n,k; int num[11]; void dfs(int a,int b) { if(b == 0) { for(int i=k;i>0;i--) { cout<<num[i]; } cout<<endl; } else{ for(int j=a;j>=1;j--) { num[b] = j; dfs(j-1,b-1); } } } int main() { cin>>n>>k; dfs(n,k); return 0; }
#include <iostream> #include <math.h> using namespace std; int n,r; int num[11]; //Store the number with an array void dfs(int a,int b) //n,k { int i,j; if(b == r) { for(int i = 0;i < r;i++) cout<<num[i]; cout<<endl; return; } else{ for(j = a;j > 0;j--) { num[b] = j; dfs(--a,b+1); //a-1ºÍ--aµÄ²î±ð = = } } } int main() { cin>>n>>r; dfs(n,0); return 0; }
-