DFS 深度优先遍历

全排列

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

1
2
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var permute = function(nums) {
var res = []
var path = []
var dfs = (path, nums) => {
if (path.length === nums.length) {
res.push(path)
}
for (let num of nums) {
if (!path.includes(num)) {
path.push(num)
dfs(path.slice(), nums)
path.pop()
}
}
}
dfs(path, nums)
return res
}