重排的字符串字符串

2023-09-11 02:16:35 作者:〆太过虚伪

由于字符串,打印其所有排列。要做到这一点,我想出了下面的程序。

Given the String, print all its permutations. To do that, i came up with the following program.

public static char[] swap(char[] input, int i, int j) {
        char temp;
        temp = input[i];
        input[i] = input[j];
        input[j] = temp;

        return input;

    }

    /**
     * 
     * @param args
     */

    public static void permuteStrings(char[] inputString, int start, int finish ) {
        //Base case: When there is only single element, print the string
        if(start == finish) 
            System.out.println(inputString);
        else {
            //Recursive case: Swap first element with all the elements and permute on the 
                           // rest of string.
            for(int i = start; i <= finish; i++) {
                inputString = swap(inputString, start, i);
                permuteStrings(inputString, i + 1, finish);
                inputString = swap(inputString,start, i); //restoring the original string
            }
        }
    }

不过,对于给定的输入ABC,一切版画是

But, for the given input ABC, all it prints are

ABC
BAC

我似乎无法弄清楚的问题是什么

I cant seem to figure out what the problem is

推荐答案

想通了这个问题。问题是,在函数调用:

Figured out the problem. The problem was in the function invocation:

permuteStrings(inputString,I + 1,完成);

正确的做法应该是:

permuteStrings(inputString, start + 1, finish);