-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathres.js
71 lines (59 loc) · 1.3 KB
/
res.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
67
68
69
70
71
/**
* res.js
* @authors Joe Jiang (hijiangtao@gmail.com)
* @date 2017-04-03 21:52:31
*
* Problem: Given a collection of distinct numbers, return all possible permutations.
*
* @param {number[]} nums
* @return {number[][]}
*/
let permute = function(nums) {
let numlen = nums.length,
res = [];
if (numlen === 0) {
return res;
} else if (numlen === 1) {
res.push(nums);
return res;
}
return subpermute([], nums);
};
let subpermute = function(base, nums) {
let numlen = nums.length,
res = [];
if (numlen === 1) {
return [base.concat(nums)];
}
for (let i = 0; i < numlen; i++) {
let subarray = [];
for (let j = 0; j < numlen; j++) {
if (i === j) {
continue;
}
subarray.push(nums[j]);
}
let newbase = base.concat([nums[i]]);
res = res.concat(subpermute(newbase, subarray));
}
return res;
};
/**
* @param {number[]} nums
* @return {number[][]}
*/
var permute = function(nums) {
const len = nums.length;
if (!len) return [];
const res = [];
const enmurate = (preArr, candidates) => {
if (candidates.length === 1) return res.push([...preArr, ...candidates]);
for (let i = 0; i < candidates.length; i++) {
const temp = candidates.slice();
temp.splice(i, 1);
enmurate([...preArr, candidates[i]], temp);
}
}
enmurate([], nums.slice());
return res;
};