The title description enters a string that prints out all the permutations of the characters in the string, in the dictionary order. For example, enter the string ABC and print out all the strings abc,acb,bac,bca,cab and CBA that can be arranged by the character A,b,c.analysis: The whole permutation problem belongs to the typical recursive problem, for the recursive problem, the first thing we need to do is to find the exit of the recursive function, that is, the recursive termination condition, find the relationship between F (n) and F (n-1), we f (n) To place the nth character at any one of the permutations of the n-1 character. Find out the arrangement of ownership and then sort the dictionary. The code looks like this:
1 Importjava.util.ArrayList;2 Public classSolution {3 PublicArraylist<string>permutation (String str) {4 returnfindpermutationstr (str);5 6 }7 Private StaticArraylist<string>Findpermutationstr (stringstr) {8Arraylist<string> strlist=findpermutations (str);9Arraylist<string> StrList2 =NewArraylist<string>();Ten for(inti = 0; I < strlist.size (); i++) { One if(!Strlist2.contains (Strlist.get (i))) { A Strlist2.add (Strlist.get (i)); - } - the } -String tmpstring =NULL; - //[Aabc, Abac, ABCA, AACB, Acab, ACBA, BAAC, Baca, BCAA, Caab, Caba , - //Cbaa] + for(inti = 0; I < strlist2.size (); i++) { - for(intj = 0; J < Strlist2.size ()-1-i; J + +) { + if(Comparestr (Strlist2.get (j), Strlist2.get (j+1)) >0) { ATmpstring =Strlist2.get (j); atStrlist2.set (J, Strlist2.get (j + 1)); -Strlist2.set (j + 1, tmpstring); - } - } - } - returnStrList2; in } - Private StaticArraylist<string>findpermutations (String str) { toArraylist<string> strlist =NewArraylist<string>(); + if(str.length () = = 0) { - returnstrlist; the } * if(str.length () = = 1) { $ Strlist.add (str);Panax Notoginseng returnstrlist; - } the if(str.length () = = 2) { + Char[] ChArry =Str.tochararray (); A Strlist.add (str); the if(charry[0]! = charry[1]) { +String s =NewString (New Char[] {charry[1], charry[0] }); - Strlist.add (s); $ } $ - returnstrlist; - } the -arraylist<string> substrpermutation Sensitive word indpermutations (str.substring (1));Wuyi CharFirstchar = Str.charat (0); the for(String s:substrpermutations) { -String tmpstr = Firstchar +s; Wu Strlist.add (TMPSTR); - Char[] Chararry =Tmpstr.tochararray (); About for(inti = 0; I < Tmpstr.length ()-1; i++) { $ Chart =Chararry[i]; -Chararry[i] = chararry[i + 1]; -Chararry[i + 1] =T; -Strlist.add (NewString (Chararry)); A } + } the returnstrlist; - } $ the Static intcomparestr (String str1, String str2) { the if(Str1.length ()! =str2.length ()) { the returnStr1.length () > Str2.length ()? 1:-1; the } - for(inti = 0; I < str1.length (); i++) { in if(Str1.charat (i) = =Str2.charat (i)) { the Continue; the } About returnStr1.charat (i) > Str2.charat (i)? 1:-1; the the } the return0; + } -}
"The sword refers to offer" 20, the arrangement of strings