题解 | #字符串的排列#
字符串的排列
http://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7
主要思想:
-通过回溯法将字符串中的字符排列都排列出来,但是可能会有重复的排列
-利用Set去重
import java.util.*;
public class Solution {
ArrayList<String> result = new ArrayList<>();
StringBuilder sb = new StringBuilder();
public ArrayList<String> Permutation(String str) {
// 标记数组
boolean[] used = new boolean[str.length()];
backTrack(str, used);
// 利用Set去重
Set<String> set = new HashSet<>(result);
ArrayList<String> res = new ArrayList<>();
for(String s : set) {
res.add(s);
}
return res;
}
public void backTrack(String str, boolean[] used) {
if(sb.length() == str.length()) {
result.add(sb.toString());
return;
}
for(int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if(used[i] == false) {
used[i] = true;
sb.append(c);
backTrack(str, used);
sb.deleteCharAt(sb.length() - 1);
used[i] = false;
}
}
}
}