生成可重集的排列

生成可重集的排列

发现自己菜的连可重集的排列都求不出来。于是今天看懂代码,来分析一波。

首先想能不能用非可重集做。显然是错的,因为同一种排列会被计算多次。所以,应该将同一类的数提取出来,统一填充。体现在算法中,就是先排序,然后找出每一类的数,在个数不超的情况下,随便填。

代码来源

#include <iostream>
#include <algorithm>
using namespace std;

int n, a[1010], p[1010];
bool cmp(int a, int b){
    return a < b;
}
void print_permutation(int cur){   //cur 表示当前确定的元素位置;
    if(cur == n){
        for(int i = 0; i < n-1; ++i){
            cout << a[i] << ' ';
        }
        cout << a[n-1] << endl;
    }
    else{
        for(int i = 0; i < n; ++i){
            if(!i || p[i] != p[i-1]){  //枚举的i应该不重复,不遗漏的取遍所有的p[i]值;
                int c1 = 0, c2 = 0;
                for(int j = 0; j < n; ++j){
                    if(p[j] == p[i])  //p数组中p[i]出现的次数;
                        ++c1;
                }
                for(int j = 0; j < cur; ++j){
                    if(a[j] == p[i])  //a数组中p[i]目前出现的次数;
                        ++c2;
                }
                if(c2 < c1){
                    a[cur] = p[i];
                    print_permutation(cur+1);
                }
            }
        }
    }
}
int main()
{
    int count(0), a;
    while(cin >> a){
        p[count++] = a;
    }
    n = count;
    sort(p, p+n, cmp);
    print_permutation(0);
}
原文地址:https://www.cnblogs.com/MyNameIsPc/p/8446756.html