算法空间/Leetcode/字符串全排列:修订间差异
来自康健生活
| (未显示同一用户的5个中间版本) | |||
| 第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 暴力搜索 === | === 实现 1 暴力搜索 === | ||
<syntaxhighlight lang="javascript" highlight="10"> | <syntaxhighlight lang="javascript" highlight="10"> | ||
| 第63行: | 第49行: | ||
[[文件: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( | let res = [] | ||
let path = [] | |||
backtracking(str, str.length, []) | |||
return res | |||
function backtracking(origin, len, used) { | |||
if (path.length === len) { | |||
res.push(path.join('')) | |||
return | |||
} | |||
for (let i = 0; i < len; i++) { | |||
if (used[i]) continue | |||
path.push(origin[i]) | |||
used[i] = true | |||
backtracking(origin, len, used) | |||
path.pop() | |||
used[i] = false | |||
} | |||
} | |||
} | |||
</syntaxhighlight> | |||
} | |||
=== 结论 === | === 结论 === | ||
[[文件:Leetcode-字符串全排列-3.png|700px|无|Leetcode-字符串全排列-3]] | [[文件:Leetcode-字符串全排列-3.png|700px|无|Leetcode-字符串全排列-3]] | ||
=== 实现 3 === | === 实现 3 交换法 === | ||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
var permute = function( | var permute = function (str) { | ||
let res = [] | |||
traverse(Array.from(str), 0, str.length - 1, res) | |||
return res | |||
} | } | ||
function | function swap(arr, prevIndex, nextIndex) { | ||
let temp = arr[prevIndex] | |||
arr[prevIndex] = arr[nextIndex] | |||
arr[nextIndex] = temp | |||
} | |||
function traverse(arr, offset, lastIndex, cup) { | |||
if (offset === lastIndex) { | |||
cup.push(arr.join('')) | |||
return | |||
} | |||
for (let i = offset; i <= lastIndex; i++) { | |||
// 交换值改变数组值的排序 | |||
swap(arr, i, offset) | |||
traverse(arr, offset + 1, lastIndex, cup) | |||
// 回溯到上一个状态 | |||
swap(arr, i, offset) | |||
} | |||
} | } | ||
</syntaxhighlight> | |||
=== 结论 === | === 结论 === | ||
交换法是通过一层一层的<code>约束</code>遍历条件,将整个计算过程构建成<code>树</code> | 交换法是通过一层一层的<code>约束</code>遍历条件,将整个计算过程构建成<code>树</code>。我个人倾向于理解这个排列为过程导向,通过构建过程函数,获取最终结果。而<code>树</code>是抽象出来的一种数学结构。 | ||
[[文件:Leetcode-字符串全排列-4.png|700px|无|Leetcode-字符串全排列-4]] | [[文件:Leetcode-字符串全排列-4.png|700px|无|Leetcode-字符串全排列-4]] | ||
=== 实现 4 字典序 === | |||