输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c
所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
public class Solution {
public ArrayList<String> Permutation(String str)
{
ArrayList<String> res = new ArrayList<String>();
if(str.length()==0|| str==null) return res;
helper(res,0,str.toCharArray());
Collections.sort(res);
return res;
}
public void helper( ArrayList<String> res, int index, char[] s)
{
if(index == s.length-1) res.add(new String(s));
for(int i=index;i<s.length;i++)
{
if(i == index||s[index]!=s[i])
{
swap(s,index,i);
helper(res,index+1,s);
swap(s,index,i);
}
}
}
public void swap(char[] t, int i, int j)
{
char c=t[i];
t[i]=t[j];
t[j]=c;
}
public static void main(String[] args)
{
Solution so = new Solution();
String s = "abc";
ArrayList<String> t =so.Permutation(s);
System.out.println(t.toString());
}
}