题解 | #字符串的排列#
字符串的排列
https://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7
利用回溯思想:与解决有重复数字的全排列解法 相同
ArrayList<String> res = new ArrayList<>();
public ArrayList<String> Permutation (String str) {
// write code here
StringBuilder path = new StringBuilder();
boolean[] used = new boolean[str.length()];
char[] strArr = str.toCharArray();
// Arrays.sort(strArr, (c1, c2) -> Character.compare(c1, c2));
Arrays.sort(strArr);
back_tracking(strArr, path, used);
return res;
}
public void back_tracking(char[] str, StringBuilder path, boolean[] used) {
if (path.length() == str.length) {
res.add(new String(path));
}
for (int i = 0; i < str.length; i++) {
if (used[i] == true || i > 0 && str[i] == str[i-1]
&& used[i-1] == false){
continue;
}
path.append(str[i]);
used[i] = true;
back_tracking(str, path, used);
path.deleteCharAt(path.length() - 1);
used[i] = false;
}
}