标签:
1 import java.util.ArrayList; 2 import java.util.Collections; 3 import java.util.HashSet; 4 import java.util.List; 5 import java.util.Set; 6 /** 7 *输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba 8 * 9 *输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。按字典序打印出该字符串中字符的所有排列 10 */ 11 public class Solution { 12 public ArrayList<String> Permutation(String str) { 13 if(str==null){ 14 return null; 15 } 16 char[] ary= str.toCharArray(); 17 Set<String> set = new HashSet<String>(); 18 List<Integer> flag = new ArrayList<Integer>(); 19 StringBuilder sbl=new StringBuilder(); 20 int index=0; 21 this.handler(ary,sbl,set,flag,index); 22 ArrayList<String> list = new ArrayList<String>(); 23 list.addAll(set); 24 Collections.sort(list); 25 return list; 26 } 27 public void handler(char[] ary ,StringBuilder sb,Set<String> set ,List<Integer> flag ,int index){ 28 for(int i = 0 ; i< ary.length ; i++){ 29 30 if(sb.length()>index){ 31 sb.delete(index,sb.length()); 32 while(index<flag.size()){ 33 flag.remove(index); 34 } 35 } 36 if(!flag.contains(i)){ 37 sb.append(ary[i]); 38 flag.add(i); 39 if(sb.length()<ary.length){ 40 this.handler(ary,sb,set,flag,index+1); 41 } 42 if(sb.length()==ary.length){ 43 set.add(sb.toString()); 44 } 45 } 46 } 47 } 48 }
标签:
原文地址:http://www.cnblogs.com/excite/p/4586661.html