生成字符数组的所有排列 [英] Generating all permutation of a character array

查看:98
本文介绍了生成字符数组的所有排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 combination.

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

But when I tried to implement it using recursion it gave me only two string for a string of length 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;
    }

我期待打印6个字符串。

I am expecting 6 string to be printed.

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

expected: 123, 132, 213, 231, 312, 321

推荐答案

方法 printPermutation 是递归的核心。它没有正确捕获开始结束索引。这很重要,因为你试图交换块

The method printPermutation is the core of your recursion. It doesn't capture the start and end indices properly. This is important because you are trying to swap in chunks

以下更改应该可以使它工作。

Following change should make it work.

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;
}

这篇关于生成字符数组的所有排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆