容易想的方法:
class Solution {
public void dfs (char[] c_str, int[] used, int depth, int len, StringBuffer sb, List<String> res) {
if (depth == len) {
String temp = new String(sb);
if (!res.contains(temp)) {
res.add(temp);
return;
}
}
for (int i = 0; i < len; i++) {
if (used[i] != 1) {
sb.append(c_str[i]);
used[i] = 1;
dfs(c_str, used, depth + 1, len, sb, res);
used[i] = 0;
sb.deleteCharAt(sb.length()-1);
}
}
}
public String[] permutation(String s) {
char[] c_str = s.toCharArray();
int len = c_str.length;
if (len == 0) {
return null;
}
List<String> res = new ArrayList<String>();
StringBuffer sb = new StringBuffer();
int[] used = new int[len];
dfs(c_str, used, 0, len, sb, res);
return res.toArray(new String[res.size()]);
}
}
会超出时间限制
改进的算法:
class Solution {
public void dfs (char[] c_str, int[] used, int depth, int len, StringBuffer sb, List<String> res) {
if (depth == len) {
res.add(new String(sb));
return;
}
for (int i = 0; i < len; i++) {
if (used[i] == 1 || (i > 0 && c_str[i] == c_str[i - 1] && used[i - 1] == 0)) { // 剪枝
continue;
}
sb.append(c_str[i]);
used[i] = 1;
dfs(c_str, used, depth + 1, len, sb, res);
used[i] = 0;
sb.deleteCharAt(sb.length()-1);
}
}
public String[] permutation(String s) {
char[] c_str = s.toCharArray();
int len = c_str.length;
if (len == 0) {
return null;
}
Arrays.sort(c_str);
List<String> res = new ArrayList<String>();
StringBuffer sb = new StringBuffer();
int[] used = new int[len];
dfs(c_str, used, 0, len, sb, res);
return res.toArray(new String[res.size()]);
}
}