Getting permutations of an int[] removing duplicates sets

后端 未结 5 1115
有刺的猬
有刺的猬 2020-12-11 23:06

I have an [] of integers 1<=N<=100 , How can i get permutations of this array? -> Array may contain duplicates, so resulting set of permutations can be duplicate, so

5条回答
  •  难免孤独
    2020-12-11 23:20

    If it is acceptable to first sort the elements lexically, then you can your lexical permutation. Including an algorithm which does it for an array of int, easily modifiable to strings.

    public static boolean permuteLexically(int[] data) {
        int k = data.length - 2;
        while (data[k] >= data[k + 1]) {
            k--;
            if (k < 0) {
                return false;
            }
        }
        int l = data.length - 1;
        while (data[k] >= data[l]) {
            l--;
        }
        swap(data, k, l);
        int length = data.length - (k + 1);
        for (int i = 0; i < length / 2; i++) {
            swap(data, k + 1 + i, data.length - i - 1);
        }
        return true;
    }
    

    Example of how to use it

    public static void main(String[] args) {
        int[] data = { 1,2,3 };
        do {
            System.err.println(Arrays.toString(data));
        } while(Util.permuteLexically(data));
    }
    

    Using this with [1,2,3] you get

    [1, 2, 3]
    [1, 3, 2]
    [2, 1, 3]
    [2, 3, 1]
    [3, 1, 2]
    [3, 2, 1]
    

    with [1,1,3] you instead get

    [1, 1, 3]
    [1, 3, 1]
    [3, 1, 1]
    

    which is what you asked for I think.

    Since the method retunes the "next" permutation in lexicographically order it is important that the elements are ordered. Starting with [3, 2, 1] you get no more permutations (compare to example above).

提交回复
热议问题