Generating all permutation of a character array

后端 未结 2 2035
独厮守ぢ
独厮守ぢ 2021-01-19 15:19

After reading so many post of \"generating permutation of string\", I tried to write it in Java. 1) Take the first character start swapping with rest of the character in the

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-19 15:48

    The general idea of your permutation algorithm is correct, but you forgot to handle some of possible cases there.

    First. You should add printPermutation(a, i + 1) before going into loop.

    Second. Call printPermutation(a, i + 1) instead of printPermutation(a, x) in the loop.

    public static void main(String[] args) {
        char a[]= "1234".toCharArray();
        printPermutation(a, 0);
    }
    
    private static void printPermutation(char[] a, int i) {
        if (i == a.length - 1) System.out.println(new String(a));
        else {
            printPermutation(a, i + 1);
            for (int x = i + 1; x < a.length; x++) {
                swap(a, i, x);
                printPermutation(a, i + 1);
                reswap(a, i, x);
            }
        }
    }
    
    private static void swap(char[] a, int i, int x) {
        char tmp = a[i];
        a[i] = a[x];
        a[x] = tmp;
    }
    
    private static void reswap(char[] a, int i, int x) {
        swap(a, i, x);
    }
    

提交回复
热议问题