LeetCode 剑指 Offer 38. 字符串的排列
题目描述
输入一个字符串,打印出该字符串中字符的所有排列。
你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。
示例:
输入:s = "abc"
输出:["abc","acb","bac","bca","cab","cba"]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zi-fu-chuan-de-pai-lie-lcof
Java代码
class Solution {
List<String> res = new LinkedList<>();
char[] c;
public String[] permutation(String s) {
c = s.toCharArray();
DFS(0);
return res.toArray(new String[res.size()]);
}
void DFS(int x) {
if(x == c.length - 1){
res.add(String.valueOf(c));
return;
}
HashSet<Character> set = new HashSet<>();
for(int i = x; i < c.length; ++i){
if(set.contains(c[i]))
continue;
set.add(c[i]);
swap(x, i);
DFS(x + 1);
swap(x, i);
}
}
void swap(int x1, int x2){
char t = c[x1];
c[x1] = c[x2];
c[x2] = t;
}
}

浙公网安备 33010602011771号