題目:無重復字符串的排列組合
輸入:S = "qwe"
輸出:["qwe", "qew", "wqe", "weq", "ewq", "eqw"]
示例2
輸入:S = "ab"
輸出:["ab", "ba"]
提示:
字符都是英文字母。
字符串長度在[1, 9]之間。
分析
經典的回溯問題,題目要求字符串的每個字符都不相同,我剛開始認為輸入字符串可能有重復的字符,所以加個段去重的代碼,最后提交時候發現不去重也可以測試通過。
代碼
class Solution {
public:
vector<string> permutation(string S) {
{// 多余的
sort(S.begin(), S.end());
auto it = std::unique(S.begin(), S.end());
S.resize(std::distance(S.begin(), it));
}
string path;
used.resize(S.size(), false);
dfs(S, path);
return ret;
}
vector<string> ret;
vector<bool> used;
void dfs(string& S, string& path) {
if (path.size() == S.size()) {
ret.push_back(path);
return;
}
for (int i = 0, size = S.size(); i < size; ++i) {
if (used[i]) continue;
used[i] = true;
path.push_back(S[i]);
dfs(S, path);
used[i] = false;
path.pop_back();
}
}
};
代碼精進之路
代碼精進之路,我們一起成長!