组合数

来源:互联网 发布:永恒之塔数据库 编辑:程序博客网 时间:2024/05/16 10:40


组合数

时间限制:3000 ms  |  内存限制:65535 KB
难度:3
描述
找出从自然数1、2、... 、n(0<n<10)中任取r(0<r<=n)个数的所有组合。
输入
输入n、r。
输出
按特定顺序输出所有组合。
特定顺序:每一个组合中的值从大到小排列,组合之间按逆字典序排列。
样例输入
5 3
样例输出
543542541532531521432431421321
来源
代码:
#include <set>#include <algorithm>#include <iostream>using namespace std;struct myComp {//自定义set比较函数,使set容器内的数按照从小到大排列 bool operator()(const int &a, const int &b) {if(a != b)return a > b;else return a > b;}};bool cmp(int a, int b) {//自定义sort比较函数,使按照从小到大排列 return a > b;}int main(){int n, r;  int a[15];set<int, myComp> s;   //定义set容器s,存放符合要求的数 cin >> n >> r;for(int i = 0; i < n; i++) {a[i] = n-i;}sort(a, a+n);do{//使用next_permutation进行全排列,判断每一次排列的前r个数字组成的数是否满足情况 int i;for(i = 0; i < r-1; i++) {if(a[i] > a[i+1]);else break;}if(i == r-1){int sum = 0;for(int i = 0; i < r; i++) {sum = 10*sum + a[i];}s.insert(sum);}}while(next_permutation(a, a+n));set<int, myComp>::iterator it;   //输出满足情况的所有答案 for(it = s.begin(); it != s.end(); it++) {cout << *it << endl;}return 0;}


0 0
原创粉丝点击