一、题目内容 中等

给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

示例1:

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

示例2:

输入:nums = [0,1] 输出:[[0,1],[1,0]]

示例3:

输入:nums = [1] 输出:[[1]]

二、解题思路

要进行全排列,那么需要遍历过程,肯定每次都要从 nums 的第一个元素开始。
重点是需要排除已经加入 path 的元素。
当 path 的长度等于 nums 的长度,说明已经完成一种全排列,将 path 加入 res。
11. 全排列(46) - 图1

三、具体代码

  1. /**
  2. * @param {number[]} nums
  3. * @return {number[][]}
  4. */
  5. var permute = function (nums) {
  6. const path = []
  7. const res = []
  8. const len = nums.length
  9. const backTracking = () => {
  10. if (path.length === len) {
  11. res.push(path.map(i => i))
  12. return
  13. }
  14. for (let i = 0; i < len; i++) {
  15. if (path.includes(nums[i])) continue
  16. path.push(nums[i])
  17. backTracking()
  18. path.pop()
  19. }
  20. }
  21. backTracking()
  22. return res
  23. };

四、其他解法