The Wayback Machine - https://web.archive.org/web/20201129064058/https://github.com/sl1673495/leetcode-javascript/issues/68
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

全排列-46 #68

Open
sl1673495 opened this issue Jun 11, 2020 · 0 comments
Open

全排列-46 #68

sl1673495 opened this issue Jun 11, 2020 · 0 comments

Comments

@sl1673495
Copy link
Owner

@sl1673495 sl1673495 commented Jun 11, 2020

给定一个 没有重复 数字的序列,返回其所有可能的全排列。

示例:

输入: [1,2,3]
输出:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

把排列的问题分治为小问题,由小问题的递归推断出最后的解。

[1, 2] 可以分割为 1permute([2]) 的所有组合,也可以分割为 2permute([1])的所有组合。

[1, 2, 3] 可以分割为 3permute([1, 2]) 的所有组合(上一步已经求得),也可以分为 2permute([1, 3])的所有组合,以此类推。

image

let permute = function (nums) {
  let n = nums.length
  if (n === 1) {
    return [nums]
  }

  let res = []
  for (let i = 0; i < n; i++) {
    let use = nums[i]
    let rest = nums.slice(0, i).concat(nums.slice(i + 1, n))
    let restPermuteds = permute(rest)
    for (let restPermuted of restPermuteds) {
      res.push(restPermuted.concat(use))
    }
  }

  return res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
1 participant
You can’t perform that action at this time.