输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则按字典序打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
import java.util.*;
public class Solution {
private String change (char[] a) {
StringBuilder res = new StringBuilder();
for (char value: a) {
res.append(value);
}
return res.toString();
}
private void solve(char[] a, ArrayList<String> ans, int index, int length) {
if (index == length - 1) {
String res = change(a);
ans.add(res);
} else {
for (int i = index; i < length; i++) {
char tmp = a[i];
a[i] = a[index];
a[index] = tmp;
solve(a, ans, index + 1, length);
// 消除上一层递归的影响
tmp = a[i];
a[i] = a[index];
a[index] = tmp;
}
}
}
public ArrayList<String> Permutation(String str) {
char[] a = str.toCharArray();
ArrayList<String> ans = new ArrayList<>();
solve(a, ans, 0, a.length);
// 去重
ans = new ArrayList<String>(new HashSet<String>(ans));
// 排序
Collections.sort(ans);
return ans;
}
}