Generating all permutations of a given string

前端 未结 30 1624
我寻月下人不归
我寻月下人不归 2020-11-21 06:35

What is an elegant way to find all the permutations of a string. E.g. permutation for ba, would be ba and ab, but what about longer st

30条回答
  •  别那么骄傲
    2020-11-21 06:56

    All the previous contributors have done a great job explaining and providing the code. I thought I should share this approach too because it might help someone too. The solution is based on (heaps' algorithm )

    Couple of things:

    1. Notice the last item which is depicted in the excel is just for helping you better visualize the logic. So, the actual values in the last column would be 2,1,0 (if we were to run the code because we are dealing with arrays and arrays start with 0).

    2. The swapping algorithm happens based on even or odd values of current position. It's very self explanatory if you look at where the swap method is getting called.You can see what's going on.

    Here is what happens: enter image description here

    public static void main(String[] args) {
    
            String ourword = "abc";
            String[] ourArray = ourword.split("");
            permute(ourArray, ourArray.length);
    
        }
    
        private static void swap(String[] ourarray, int right, int left) {
            String temp = ourarray[right];
            ourarray[right] = ourarray[left];
            ourarray[left] = temp;
        }
    
        public static void permute(String[] ourArray, int currentPosition) {
            if (currentPosition == 1) {
                System.out.println(Arrays.toString(ourArray));
            } else {
                for (int i = 0; i < currentPosition; i++) {
                    // subtract one from the last position (here is where you are
                    // selecting the the next last item 
                    permute(ourArray, currentPosition - 1);
    
                    // if it's odd position
                    if (currentPosition % 2 == 1) {
                        swap(ourArray, 0, currentPosition - 1);
                    } else {
                        swap(ourArray, i, currentPosition - 1);
                    }
                }
            }
        }
    

提交回复
热议问题