The full arrangement of strings, the specific content is as follows
Enter a string and print out all the arrangements of characters in the string in dictionary order. For example, input the string abc, print out all the strings abc, acb, bca, cab and cba that can be arranged by the characters a, b, c. Please output the results alphabetical order.
Adopting the idea of recursion:
Divide strings that need to be fully arranged into two parts:
(1) The first character of the string;
(2) All characters after the first character;
Find all characters that may appear in the first position; exchange the first character and the following characters at once;
Fix the first character and find the full arrangement of all characters after the first character. All characters following the first character can be divided into two parts;
Java code:
import java.util.ArrayList; import java.util.TreeSet; public class Solution { public ArrayList<String> Permutation(String str) { ArrayList<String> res = new ArrayList<String>(); if(str==null||str.length()==0) { return res; } char[] charArray = str.toCharArray(); //Output in order of input dictionary TreeSet<String> tempRes = new TreeSet<String>(); PermutationCore(charArray,tempRes,0); res.addAll(tempRes); return res; } private void PermutationCore( char[] charArray,TreeSet<String> tempRes,int loc) { if(charArray==null || charArray.length==0 || loc<0 || loc>charArray.length-1) { return ; } if(loc==charArray.length-1) { tempRes.add(String.valueOf(charArray));//Recursive exit} else { for(int i=loc;i<charArray.length;i++) { swap(charArray,i,loc);//Swap the first character with the following characters PermutationCore(charArray,tempRes,loc+1);//Sort the following characters swap(charArray,i,loc);//Swap back the previously exchanged characters so that the first character can be exchanged with other characters} } } } private void swap(char[] charArray,int i,int j) { char temp = charArray[i]; charArray[i] = charArray[j]; charArray[j] = temp; } }The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.