forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
6a4e00c
commit 711f2b7
Showing
1 changed file
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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; | ||
}; |