试题 08.07. 无重复字符串的排列组合~回溯法
参考文章:
https://mp.weixin.qq.com/s/vdB0xWuuWHaDZcFTZXZNMQ
https://leetcode-cn.com/problems/permutation-i-lcci/solution/mian-shi-ti-0807-wu-zhong-fu-zi-fu-chuan-de-pai–2/
https://leetcode-cn.com/problems/permutation-i-lcci/solution/quan-pai-lie-jiao-huan-fa-qing-xi-tu-shi-by-chen-k/
模板必须掌握:
class Solution {
List<String> list;
public String[] permutation(String S) {
list = new ArrayList<>();
dfs(S, "");
return list.toArray(new String[0]);
}
public void dfs(String S, String tmp){
if(tmp.length() == S.length()){
list.add(tmp);
return;
}
for(int j = 0; j < S.length(); j++){
if(tmp.indexOf(S.charAt(j)) != -1) continue;
dfs(S, tmp + S.charAt(j));
}
}
}
上面这种解法是很慢的,尝试怎么优化一下它
假设当前索引为k,尝试从剩下的字符串中选择出一个字符进行交换,选择的字符成为我们k位置上的字符,进行递归,直到选不出来为止。
class Solution {
List<String> list;
char[] s1;
public String[] permutation(String S) {
list = new ArrayList<>();
s1 = S.toCharArray();
dfs(0);
return list.toArray(new String[0]);
}
public void dfs(int k){
if(k == s1.length){
list.add(new String(s1));
return;
}
for(int j = k; j < s1.length; j++){
swap(s1, k, j);//交换
dfs(k + 1);
swap(s1, k, j);//回溯
}
}
public void swap(char[] s1, int k, int j){
char tmp = s1[k];
s1[k] = s1[j];
s1[j] = tmp;
}
}