leetcode 18. 4Sum
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: 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]
]
var fourSum = function (nums, target) {
nums.sort((a, b) => a - b)
var len = nums.length
return kSum(nums, len, 0, 4, target)
};
function kSum(nums, len, start, k, target) {
if (k === 2) {
return twoSum(nums, len, start, target)
} else {
var result = []
for (var i = start; i < len; i++) {
//不能是第一个
if (i != start && nums[i] == nums[i - 1]) {
continue
}
var ret = kSum(nums, len, i + 1, k - 1, target - nums[i])
if (ret.length) {
ret.forEach(function (el) {
result.push([nums[i]].concat(el))
})
}
}
return result
}
}
function twoSum(nums, len, start, target) {
var left = start;
var right = len - 1, ret = []
while (left < right) {
var sum = nums[left] + nums[right]
if (sum === target) {
ret.push([nums[left], nums[right]])
while (nums[left] == nums[left + 1]) {
left++
}
while (nums[right] == nums[right - 1]) {
right--
}
left++
right--
} else if (sum > target) {
right--
} else {
left++
}
}
return ret
}
机器瞎学/数据掩埋/模式混淆/人工智障/深度遗忘/神经掉线/计算机幻觉/专注单身二十五年