一、题目内容 中等
给定一个不含重复数字的数组 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。
三、具体代码
/**
* @param {number[]} nums
* @return {number[][]}
*/
var permute = function (nums) {
const path = []
const res = []
const len = nums.length
const backTracking = () => {
if (path.length === len) {
res.push(path.map(i => i))
return
}
for (let i = 0; i < len; i++) {
if (path.includes(nums[i])) continue
path.push(nums[i])
backTracking()
path.pop()
}
}
backTracking()
return res
};