使用许多元素计算排列

时间:2014-10-23 23:54:27

标签: c++ algorithm permutation

我试图生成一组元素的所有可能的排列。顺序无关紧要,元素可能多次出现。每个排列中的元素数量等于元素的总数。

用于计算模式之后的排列的基本递归算法(正如我在C ++中编写的,代码看起来与它类似):

elems = [0, 1, .., n-1];    // n unique elements. numbers only exemplary.
current = [];               // array of size n
perms(elems, current, 0);   // initial call

perms(array elems, array current, int depth) {
    if(depth == elems.size) print current;
    else {
        for(elem : elems) {
            current[depth] = elem;
            perms(elems, current, depth+1);
        }
    }
}

会产生大量冗余序列,例如:

0, 0, .., 0, 0
0, 0, .., 0, 1    // this
0, 0, .., 0, 2
.  .  .   .  . 
.  .  .   .  .
0, 0, .., 0, n-1
0, 0, .., 1, 0    // is the same as this
.  .  .   .  .    // many more redundant ones to follow

我试图确定何时可以跳过确切的生成值,但到目前为止还没有找到任何有用的内容。我相信我可以找到一种方法来解决这个问题,但我也确定,这背后有一条规则,我根本没有看到。

编辑:可能的解决方案+

elems = [0, 1, .., n-1];       // n unique elements. numbers only exemplary.
current = [];                  // array of size n
perms(elems, current, 0, 0);   // initial call

perms(array elems, array current, int depth, int minimum) {
    if(depth == elems.size) print current;
    else {
        for(int i=minimum; i<elems.size; i++) {
            current[depth] = elems[i];
            perms(elems, current, depth+1, i);
        }
    }
}

2 个答案:

答案 0 :(得分:2)

我相信一个这样的规则是让每个序列中的元素按非递减顺序(或者如果你愿意,不增加)。

答案 1 :(得分:2)

让你的第一个位置从0到n不等。然后将你的第二个位置设为1.然后使你的第一个位置从1到n变化。然后在2 - >处设置第二个。首先从2到n,依此类推。