-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0018-4sum.js
48 lines (46 loc) · 1.39 KB
/
0018-4sum.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
/**
* @param {number[]} nums
* @param {number} target
* @return {number[][]}
*/
var fourSum = function (nums, target) {
const sortedNums = nums.sort((a, b) => a - b);
const res = [];
const quad = [];
const kSum = (k, start, target) => {
if (k > 2) {
for (let i = start; i < sortedNums.length; i++) {
if (i !== start && sortedNums[i] === sortedNums[i - 1]) {
continue;
}
quad.push(sortedNums[i]);
kSum(k - 1, i + 1, target - sortedNums[i]);
quad.pop();
}
} else {
let left = start;
let right = sortedNums.length - 1;
while (left < right) {
const sum = sortedNums[left] + sortedNums[right];
if (sum < target) {
left++;
} else if (sum > target) {
right--;
} else {
res.push(
quad.concat([sortedNums[left], sortedNums[right]])
);
left++;
while (
left < right &&
sortedNums[left] === sortedNums[left - 1]
) {
left++;
}
}
}
}
};
kSum(4, 0, target);
return res;
};