输入一个字符串,打印出该字符串中字符的所有排列。
你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。
示例:
输入:s = "abc"
输出:["abc","acb","bac","bca","cab","cba"]
限制:
1 <= s 的长度 <= 8
重复方案与剪枝: 当字符串存在重复字符时,排列方案中也存在重复方案。为排除重复方案,需在固定某位字符时,保证“每种字符只在此位固定一次”,即遇到重复字符时跳过。从 DFS 角度看,此操作称为“剪枝”。
class Solution:
def permutation(self, s: str) -> List[str]:
c, res = list(s), []
def dfs(x):
if x == len(c) - 1:
# 位置到达字符串末尾
res.append(''.join(c)) # 添加排列方案
return
dic = set()
for i in range(x, len(c)):
# 判断固定位置上是否出现重复元素
if c[i] in dic: continue # 重复,因此剪枝
dic.add(c[i])
c[i], c[x] = c[x], c[i] # 交换,固定此位为 c[i]
dfs(x + 1) # 开启固定第 x + 1 位字符
c[i], c[x] = c[x], c[i] # 恢复交换
dfs(0)
return res
class Solution {
public:
vector<string> result;
vector<string> permutation(string s) {
dfs(s, 0);
return result;
}
void dfs(string& s, int pos) {
if (/*pos >= s.size()*/pos == s.size()-1) {
// 位置到达字符串末尾
result.push_back(s);
return;
}
for (int i = pos; i < s.size(); ++i) {
// 判断固定位置上是否出现重复元素
if (judge(s, pos, i)) continue; // 如果pos和i之间有字符等于s[i],则跳过。
swap(s[pos], s[i]);
dfs(s, pos+1);
swap(s[pos], s[i]);
}
}
bool judge(string& s, int start, int end) {
for (int i = start; i < end; ++i) {
if (s[i] == s[end]) return true;
}
return false;
}
};