题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
解题思路
回溯法的思想:
具体递归思路:
import java.util.*;
public class Solution {
public ArrayList<String> Permutation(String str) {
ArrayList<String> result = new ArrayList<String>();
if(str!=null && str.length()>0)
PermutationHelper(str.toCharArray(),0,result);
Collections.sort(result);
return result;
}
public void PermutationHelper(char[] cs, int i, List<String> list){
if(i==cs.length-1) //到末尾,判断集合中有没有这个字符串,没有则加入。
{
String s = String.valueOf(cs);
if(!list.contains(s))
list.add(s);
}
else
{
for(int j = i;j<cs.length;j++)
{
swap(cs,i,j); //交换
PermutationHelper(cs,i+1,list);
swap(cs,j,i); //还原
}
}
}
public void swap(char[] cs, int i, int j){
char temp = cs[i];
cs[i] = cs[j];
cs[j] = temp;
}
}