-
Notifications
You must be signed in to change notification settings - Fork 130
/
4Sum.js
91 lines (76 loc) · 2.29 KB
/
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
The solution set must not contain duplicate quadruplets.
For example, given array S = {1 0 -1 0 -2 2}, and target = 0.
A solution set is:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)
*/
/**
* @param {number[]} nums
* @param {number} target
* @return {number[][]}
*/
var fourSum = function(nums, target) {
nums.sort(function(a, b) {
return a - b;
});
var len = nums.length,
result = [],
i;
kSum(result, [], 4, nums, target, 0, len - 1);
return result;
};
function kSum(result, curArr, k, nums, target, startIndex, endIndex) {
var len = nums.length,
start,
end,
sum,
i;
if (k >= 3) {
for (i = startIndex; i <= endIndex; i++) {
if (i > startIndex && nums[i] === nums[i - 1]) {
continue;
}
curArr.push(nums[i]);
kSum(result, curArr.concat(), k - 1, nums, target - nums[i], i + 1, endIndex);
curArr.pop();
}
}
if (k === 1) {
for (i = startIndex; i <= endIndex; i++) {
if (nums[i] === target) {
result.push(nums[i]);
}
}
}
if (k === 2) {
start = startIndex;
end = endIndex;
while (start < end) {
sum = nums[start] + nums[end];
if (sum === target) {
curArr.push(nums[start]);
curArr.push(nums[end]);
result.push(curArr.concat());
curArr.pop();
curArr.pop();
start++;
end--;
while(nums[start] === nums[start - 1]) {
start++;
}
while(nums[end] === nums[end + 1]) {
end--;
}
} else if (sum < target) {
start++;
} else {
end--;
}
}
}
}