算法空间/Leetcode/字符串全排列:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
Kangkk​(留言 | 贡献)
 
(未显示同一用户的1个中间版本)
第18行: 第18行:
<math>\frac{n!}{n_1! n_2! \cdots n_k!}</math>,其中 <math>n_{1},n_{2}\dots n_{k}</math> 是各重复字符的个数。
<math>\frac{n!}{n_1! n_2! \cdots n_k!}</math>,其中 <math>n_{1},n_{2}\dots n_{k}</math> 是各重复字符的个数。


=== 实现 1  ===
<syntaxhighlight lang="javascript">
function findPermutations(str) {
  const res = [];
  for (let i = 1; i <= 3; i +=1) {
    for (let j = 1; j <= 3; j +=1) {
      for (let k = 1; k <= 3; k +=1) {
        res.push(str[i] + str[j] + str[k]);
      }
    }
  }
  return res;
}</syntaxhighlight>
=== 实现 1 暴力搜索 ===
=== 实现 1 暴力搜索 ===
<syntaxhighlight lang="javascript" highlight="10">
<syntaxhighlight lang="javascript" highlight="10">
第64行: 第50行:
[[文件:Leetcode-字符串全排列-2.jpg|700px|none|Leetcode-字符串全排列-2]]
[[文件:Leetcode-字符串全排列-2.jpg|700px|none|Leetcode-字符串全排列-2]]
=== 实现 2 回溯剪枝  ===
=== 实现 2 回溯剪枝  ===
<syntaxhighlight lang="javascript">
<syntaxhighlight lang="javascript">var permute = function (str) {
var permute = function(nums) {
let res = []
    const res = [], path = [];
let path = []
    backtracking(nums, nums.length, []);
backtracking(str, str.length, [])
    return res;
return res
   
 
    function backtracking(n, k, used) {
function backtracking(origin, len, used) {
        if(path.length === k) {
if (path.length === len) {
            res.push(Array.from(path));
res.push(path.join(''))
            return;
return
        }
}
        for (let i = 0; i < k; i++ ) {
for (let i = 0; i < len; i++) {
            if(used[i]) continue;
if (used[i]) continue
            path.push(n[i]);
path.push(origin[i])
            console.log('递归之前', path)
used[i] = true
            used[i] = true; // 同支
backtracking(origin, len, used)
            backtracking(n, k, used);
path.pop()
            path.pop();
used[i] = false
            console.log('递归之后', path, used)
}
            used[i] = false;
}
        }
}
    }
</syntaxhighlight>
};</syntaxhighlight>


=== 结论 ===
=== 结论 ===