组合数
时间限制:
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<stdio.h>
int a[15];
int n,r;//i不能定义在这
void dfs(int c,int x){
int i;
if(x==r+1){
for(int j=1;j<=r;j++)
printf("%d",a[j]);
printf("\n");
}
for(i=c;i>0;i--){
a[x]=i;
dfs(i-1,x+1);
}
}
int main(){
while(scanf("%d%d",&n,&r)==2){
dfs(n,1);
}
return 0;
}
全排列代码:
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int Judge(string s){//是否递减
for(int i=0;i<s.size()-1;i++){
if(s[i]<=s[i+1]) return 0;
}
return 1;
}
int main()
{
int n,r;
while(cin>>n>>r){
string s,ss;
for(int i=n;i>=1;i--) s+=i+'0';
ss=s.substr(0,r);
cout<<ss<<endl;
while(prev_permutation(s.begin(),s.end())){//组合函数
if(s.substr(0,r)!=ss&&Judge(s.substr(0,r))){//不相等而且递减
ss=s.substr(0,r);
cout<<ss<<endl;
}
}
}
return 0;
}
//32
#include <stdio.h>
#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>=1;--i){
printf("%d",num[i]);
}
printf("\n");
}
else{
for(int i=x;i>=y;--i){
num[y]=i;
//printf("test=%d %d test=%d\n",i,y,num[y]);
dfs(i-1,y-1);
}
}
}
int main(){
//freopen("11.txt","r",stdin);
while(~scanf("%d%d",&n,&r)){
dfs(n,r);
}
return 0;
}