-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0046-permutations.js
66 lines (53 loc) · 1.77 KB
/
0046-permutations.js
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
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* https://leetcode.com/problems/permutations/solution/
* Time O(N!) | Space(N!)
* @param {number[]} nums
* @return {number[][]}
*/
var permute = function(nums) {
return dfs(nums)
}
var dfs = function(nums, permutation = [], permutations = []) {
const isBaseCase = nums.length === permutation.length
if (isBaseCase) return permutations.push(permutation.slice())
for (let i = 0; i < nums.length; i++) {
if (permutation.includes(nums[i])) continue;
backTrack(nums, i, permutation, permutations);
}
return permutations;
}
const backTrack = (nums, i, permutation, permutations) => {
permutation.push(nums[i])
dfs(nums, permutation, permutations)
permutation.pop()
}
/**
* https://leetcode.com/problems/permutations/solution/
* Time O(N!) | Space(N!)
* @param {number[]} nums
* @return {number[][]}
*/
var permute = function(nums) {
return bfs(nums)
}
const bfs = (nums, levels = [[]], permutations = []) => {
for (const num of nums) {
for (let i = (levels.length - 1); 0 <= i; i--) {
const previousLevel = levels.shift()
for (let index = 0; index < (previousLevel.length + 1); index++) {
const level = reArrangeSet(previousLevel, num, index)
const isBaseCase = level.length === nums.length;
if (isBaseCase) {
permutations.push(level);
continue
}
levels.push(level)
}
}
}
return permutations
}
const reArrangeSet = (previousLevel, num, index) => {
const [ before, after ] = [ previousLevel.slice(0, index), previousLevel.slice(index) ]
return [...before, num, ...after]
}