leetcode icon indicating copy to clipboard operation
leetcode copied to clipboard

46. 全排列

Open buuing opened this issue 4 years ago • 0 comments

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

示例:

输入: [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, 3]
   /       |      \
  1        2       3
 /  \     / \     / \
2    3   1   3    1  2
|    |   |   |    |  |
3    2   3   1    2  1
const permute = nums => {
  if (!nums.length) return []
  let res = []
  const dfs = (map, arr) => {
    if (arr.length === nums.length) {
      return res.push(arr.slice())
    }
    for (let i = 0; i < nums.length; i++) {
      if (map[i]) continue
      map[i] = 1
      arr.push(nums[i])
      dfs(map, arr)
      arr.pop()
      map[i] = 0
    }
  }
  dfs([], [])
  return res
}

buuing avatar Dec 22 '20 14:12 buuing