剑指 Offer 38. 字符串的排列

思路
回溯
使用set保存当前遍历中出现过的字母
遍历时,如果是当前未出现过的字母,添加到集合,交换顺序,进行回溯,回退交换
代码
class Solution {
List<String> res=new ArrayList<>();
char []c;
public String[] permutation(String s) {
c=s.toCharArray();
dfs(0);
return res.toArray(new String[res.size()]);
}
public void dfs(int index){
if(index==c.length-1){
res.add(String.valueOf(c));
return;
}
HashSet<Character> set=new HashSet<>();
for(int i=index;i<c.length;i++){
if(set.contains(c[i]))continue;
set.add(c[i]);
swap(i,index);
dfs(index+1);
swap(i,index);
}
}
public void swap(int i,int j){
char tmp=c[i];
c[i]=c[j];
c[j]=tmp;
}
}
该博客介绍了如何使用回溯算法解决字符串的所有排列问题。通过创建一个HashSet来存储遍历过程中的字符,并在递归过程中交换字符位置,实现了所有可能的字符串排列。代码中定义了`permutation`方法进行深度优先搜索(DFS),并在找到一个有效排列时将其添加到结果列表中。
357

被折叠的 条评论
为什么被折叠?



