46.Permutations

25 年 7 月 28 日 星期一
125 字
1 分钟

46. 全排列

Screenshot 2026-03-04 at 8.18.56 pm
js
/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var permute = function (nums) {
  const n = nums.length
  const path = Array(n).fill(0)
  const onPath = Array(n).fill(false)
  const ans = []

  // 枚举 path[i] 填 nums 的哪个数
  const dfs = (i) => {
    if (i === n) {
      ans.push(path.slice())
      return
    }
    // 枚举选哪个
    for (let j = 0; j < n; j++) {
      if (onPath[j]) {
        continue
      } else {
        onPath[j] = true
        path[i] = nums[j]
        dfs(i + 1)
        onPath[j] = false
        // 注意 path 无需恢复现场,因为排列长度固定,直接覆盖就行
      }
    }
  }
  dfs(0)
  return ans
}

文章标题:46.Permutations

文章作者:Sirui Chen

文章链接:https://blog.siruichen.me/posts/46permutations[复制]

最后修改时间:


商业转载请联系站长获得授权,非商业转载请注明本文出处及文章链接,您可以自由地在任何媒体以任何形式复制和分发作品,也可以修改和创作,但是分发衍生作品时必须采用相同的许可协议。
本文采用CC BY-NC-SA 4.0进行许可。