题目
算法思路
当字符串中没有重复的字符时,共有 n ! n! n! 种不同排列,即,先固定第一位字符(有 n 种选择),再固定第二位字符(有 n-1 种选择),…,最后固定第 n 位字符(1种选择),很容易想到递归的方法。但题设中并未限制输入的字符串中没有重复的字符,所以需要剪枝,保证在固定某一位的字符时,遇到重复的字符直接跳过。
递归函数dfs():
- 递归参数:当前固定位 x x x
- 终止条件:
x = c.length - 1
时,代表所有位都已固定,则将当前排列转化为字符串并加入结果列表 r e s res res - 递推过程:初始化一个集合
s
e
t
set
set 用于排除重复的字符,
i
∈
[
x
,
c
.
l
e
n
g
t
h
]
i\in [x,\ c.length]
i∈[x, c.length]
1.剪枝:若 c [ i ] c[i] c[i] 在 s e t set set 中,代表该字符是重复字符,跳过
2.将 c [ i ] c[i] c[i] 加入 s e t set set 中,以便之后再次遇到时剪枝
3.固定字符:将 c [ i ] c[i] c[i] 与 c [ x ] c[x] c[x] 交换,即,固定 c [ i ] c[i] c[i] 为当前位字符
4.开启下层递归:调用dfs(x + 1)
,开始固定下一位
5.还原交换:将 c [ i ] c[i] c[i] 与 c [ x ] c[x] c[x] 交换
具体代码
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()]);//将结果列表转换为一个数组再返回
}
//递归函数
private 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(i, x);//交换c[i]与c[x]
dfs(x + 1);//开启下层递归,开始固定下一位
swap(i, x);//还原交换
}
}
//交换函数
private void swap(int a, int b){
char tmp = c[a];
c[a] = c[b];
c[b] = tmp;
}
}
复杂度分析
- 时间复杂度: O ( n ! n ) O(n!n) O(n!n),n 为 字符串 s 的长度。方案数为 n ! n! n!,每一种方案中字符串拼接操作需要 O ( n ) O(n) O(n)。
- 空间复杂度: O ( n 2 ) O(n^2) O(n2), 全排列的递归深度为 n,使用栈空间大小为 O ( n ) O(n) O(n);递归中辅助集合 Set 累计存储的字符数量最多为 n + ( n − 1 ) + . . . + 2 + 1 = ( n + 1 ) n 2 n+(n−1)+...+2+1=\frac{(n+1)n}{2} n+(n−1)+...+2+1=2(n+1)n ,即占用 O ( n 2 ) O(n^2) O(n2)的额外空间。