-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path46.全排列.js
More file actions
53 lines (50 loc) · 1020 Bytes
/
46.全排列.js
File metadata and controls
53 lines (50 loc) · 1020 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
* @lc app=leetcode.cn id=46 lang=javascript
*
* [46] 全排列
*/
// @lc code=start
/**
* @param {number[]} nums
* @return {number[][]}
*/
// 方法1
// var permute = function(nums) {
// const result = []
// function buildPath(path) {
// if(path.length === nums.length) {
// return result.push([...path])
// }
// for(let i = 0; i< nums.length; i++) {
// if(path.includes(nums[i])) {
// continue
// }
// buildPath([...path, nums[i]])
// }
// }
// buildPath([])
// return result
// };
// 方法2
var permute = function(nums) {
const used = new Array(nums.length).fill(false)
const result = []
function dfs(path) {
if(nums.length === path.length) {
return result.push([ ...path ])
}
for(let i = 0; i< nums.length; i++) {
if(used[i]) {
continue
}
path.push(nums[i])
used[i] = true
dfs(path)
path.pop(nums[i])
used[i] = false
}
}
dfs([])
return result
}
// @lc code=end