生成字符数组的所有排列

dea*_*mer 3 java string algorithm recursion data-structures

在阅读了很多"生成字符串排列"的帖子之后,我尝试用Java编写它.1)将第一个字符开始与组合中剩余的字符进行交换.

但是当我尝试使用递归实现它时,它只给了我一个长度为3的字符串的字符串:(.

public static void main(String[] args) {
    char a[]= "123".toCharArray();
    printPermutation(a,0);

}
private static void printPermutation(char[] a, int i) {
    if(i==a.length-1)
        System.out.println(new String(a));
    else{
        for(int x=i+1;x<a.length;x++)
        {
            swap(a,i,x);
            printPermutation(a,x );
            swap(a,i,x);
        }
    }
}
private static void swap(char[] a, int i, int x) {
        char t=a[i];
        a[i]=a[x];
        a[x]=t;
    }
Run Code Online (Sandbox Code Playgroud)

我期待打印6个字符串.

预期:123,132,213,231,312,321

Jav*_*per 6

该方法printPermutation是递归的核心.它不能正确捕获开始结束指数.这很重要,因为您正在尝试交换块

改变之后应该让它发挥作用.

public static void main(String[] args) {
    char a[]= "123".toCharArray();
    printPermutation(a, 0, a.length);
}

private static void printPermutation(char[] a, int startIndex, int endIndex) {
    if (startIndex == endIndex)//reached end of recursion, print the state of a
        System.out.println(new String(a));
    else {
        //try to move the swap window from start index to end index
        //i.e 0 to a.length-1
        for (int x = startIndex; x < endIndex; x++) {
            swap(a, startIndex, x);
            printPermutation(a, startIndex + 1, endIndex);
            swap(a, startIndex, x);
        }
    }
}

private static void swap(char[] a, int i, int x) {
    char t = a[i];
    a[i] = a[x];
    a[x] = t;
}
Run Code Online (Sandbox Code Playgroud)