无重复字符串的排列组合

466 阅读1分钟

这题很离谱,看着答案我都写不出来

无重复字符串的排列组合。编写一种方法,计算某字符串的所有排列组合,字符串每个字符均不相同。 示例1: 输入:S = "qwe" 输出:["qwe", "qew", "wqe", "weq", "ewq", "eqw"] 示例2: 输入:S = "ab" 输出:["ab", "ba"]

class Solution {
public:
vector ans;
vector permutation(string S) {
dfs(S, 0);
return ans;
}
void dfs(string S, int idx) {
int n = S.size();
if (idx == n) ans.emplace_back(S);
for (int i = idx; i != n; ++i) {
string tmp = S;
swap(tmp[idx], tmp[i]);
dfs(tmp, idx + 1);
}
}
};

好难,一个是可以把函数的定义放在所有函数之前

然后是函数的类型为空,但仍然可以通过.push_back或.emplace_back来返回值,这两个是一样的

像这个子函数dfs里面基本都是用的temp,idx这些可变的值,

这个代码精巧的让我理解都理解了好久