Offer twenty-seven prove safety: string arrangement

Casual working

A string input, prints out all permutations of the characters in the string in lexicographic order. For example input string abc, abc print all strings of characters a, b, c can be arranged out, acb, bac, bca, cab and cba.

Thinking

Let's everyday ideas to solve it. Some like to do in high school when ordering combinations for a given number of three seeking their different sort order, we usually do is to say, the first fixed a number, and then taking a rest sort of a combination of numbers, then inserted therein example bc bc and cb have sorted and then inserted into a location in which there will be three six kinds of desired results. Another idea is to say that we will continue to back with the first digital exchange, after each exchange of the remaining two were arranged in a arrangement becomes a three twice.
Here we are thinking about how to implement the second method: First, aa exchange, equivalent to a carry out a fix. Then, after BC (the two) to give two results exchange, then switching ab, b for a fixed, and ac (the latter two) exchanged. Finally ac exchange, c fixed, ab (after two switching positions)
this time we can write the first portion pseudocode

for(int i=j;i<num.length;i++){
swap(num,i,j);
}
private void swap(int num[],int i,int j){
}

Then that is for the latter part of the exchange, we can take advantage of changes in the value of recursion to solve. code show as below

import java.util.ArrayList;
import java.util.*;
public class Solution {
     public ArrayList<String> Permutation(String str) {
       ArrayList<String> array=new ArrayList<String>();
    
        all(str.toCharArray(),0,array);
          Collections.sort(array);   
        return array;
        
    }
    private void all(char [] ch,int i,ArrayList<String> array)
    {
        if(i==ch.length-1){
            String val=String.valueOf(ch);
            if(!array.contains(val))
                array.add(val);
        }
        else{
            for(int j=i;j<ch.length;j++){
            swap(ch,i,j);
            all(ch,i+1,array);
            swap(ch,i,j);
        }
        }
        
    }
    private void swap(char [] ch,int i,int j){
        char temp=ch[i];
        ch[i]=ch[j];
        ch[j]=temp;
    }
}
	```
Published 47 original articles · won praise 28 · views 2703

Guess you like

Origin blog.csdn.net/weixin_44015043/article/details/105370824