NYOJ32组合数

18 篇文章 0 订阅


组合数

时间限制: 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;  
}  




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值