提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
题目描述
输入一个字符串,打印出该字符串中字符的所有排列。
你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。
示例:
输入:s = “abc”
输出:[“abc”,“acb”,“bac”,“bca”,“cab”,“cba”]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zi-fu-chuan-de-pai-lie-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题过程
解题思路
回溯法:递归函数中利用for循环遍历数组,每一次for循环交换i和index索引所对应的数组值,利用HashSet保存字符串从而去掉重复值。具体图解思想参考自:https://leetcode-cn.com/problems/zi-fu-chuan-de-pai-lie-lcof/solution/javahui-su-fa-by-cyingenohalt-12e8/
class Solution {
public String[] permutation(String s) {
HashSet<String> set = new HashSet<>();
char [] str = s.toCharArray();
dfs(0, str, set);
String[] res = new String[set.size()];
int i = 0;
for(String ss:set){
res[i++] = ss;
}
return res;
}
public void dfs(int index, char[]str, HashSet<String> set){
if(index == str.length - 1){
set.add(String.valueOf(str));
return;
}
for(int i = index; i < str.length; i++){
swap(i, index, str);
dfs(index+1, str, set);
swap(i, index, str);
}
}
public void swap(int i , int j, char []s){
char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
总结
暂时没有总结,待续。。。