题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
public ArrayList<Integer> Permutation(String str) {
ArrayList<Integer> res = new ArrayList<>();
if (str == null || str.length() == 0)
return res;
PermutationHelper(str.toCharArray(), 0, res);
return res;
}
public void PermutationHelper(char[] cs, int i, ArrayList list) {
if(i == cs.length) {
String val = String.valueOf(cs);
list.add(val);
} else {
for(int j = i; j < cs.length; ++j) {
swap(cs, i, j);
PermutationHelper(cs, i + 1, list);
swap(cs, i, j);
}
}
}
private void swap(char[] ch, int i, int j) {
if (i != j) {
char t = ch[i];
ch[i] = ch[j];
ch[j] = t;
}
}