Skip to content

全排列-46 #68

Open
Open
@sl1673495

Description

@sl1673495

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

示例:

输入: [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
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    待复习看题解或者做出来很艰难的,需要回顾。递归与回溯

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy