题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
思路:
每次将自己加入Treeset,然后依次交换自己与自己后面的每个位置的字符。这里用递归,就可以让每个都弄到。
每次换了以后,1.把自己加入。2.生出递归分支,让已经换了的字符串继续换下去。3.自己这层得复原,复原了自己的这层不换,换自己后面的换。
import java.util.ArrayList;
import java.util.TreeSet;
import java.util.Iterator;
public class Solution {
public ArrayList<String> Permutation(String str) {
ArrayList<String>list = new ArrayList<>();
TreeSet<String> treeSet = new TreeSet<>();
if(str.length()==0)return list;
findString(treeSet, str, 0);
Iterator<String>iterator = treeSet.iterator();
while(iterator.hasNext()){
list.add(iterator.next());
}
return list;
}
public void findString(TreeSet<String>treeSet,String str,int index){
if(index==str.length())return;
for(int i =index;i<str.length();i++){
char array []=str.toCharArray();
char temp = array[index];
array[index] = array[i];
array[i] = temp;
treeSet.add(new String(array.clone()));
findString(treeSet, new String(array), index+1);
temp = array[index];
array[index] = array[i];
array[i] = temp;
findString(treeSet, str, i+1);
}
}
}