Title: Enter 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. The results are output in alphabetical order. Enter a string that is not more than 9 in length (there may be a repetition of characters), and the characters include only uppercase and lowercase letters.
Idea: recursion, backtracking.
Implementation code:
ImportJava.util.*; Public classSolution { PublicArraylist<string>permutation (String str) {ArrayList<String> ret =NewArraylist<string>(); if(str = =NULL|| Str.length () <= 0) returnret; DFS (Str.tochararray (),0, ret); Collections.sort (ret); returnret; } Public voidDfsChar[] CHS,intI, arraylist<string>ret) { if(i = = Chs.length-1) {Ret.add (string.valueof (CHS)); } Else { for(intJ=i; j<chs.length; J + +) { if(i = = J | | chs[i]! =Chs[j]) {Swap (CHS, I, J); DFS (CHS, I+1, ret); Swap (CHS, I, J); } } } } Public voidSwapChar[] CHS,intIintj) {CharCH =Chs[i]; Chs[i]=Chs[j]; CHS[J]=ch; }}
Arrangement of strings