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.code
Note: The solution set must not contain duplicate quadruplets.
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.element
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]get
這道題目和解決3sum的思路是同樣的
思路是這樣的,首先咱們先不考慮去除重複的部分,把代碼寫出來,就很簡單的用for循環,當判斷最裏面的兩個數的時候用while循環.以後寫出來了,在考慮怎麼才能避免重複,就是跳過已經用過的數字就好了.io
var fourSum = function(nums, target) { let len = nums.length; if (nums.length < 4) return []; nums.sort(function(a, b){return a-b;}); var res = []; for (let i = 0; i < len-3; i++) { if (i > 0 && nums[i] == nums[i-1]) continue; for (let j = i+1; j < len-2; j++) { if (j > i + 1 && nums[j] == nums[j-1]) continue; let lo = j+1, hi = len-1; let temp; while(lo < hi) { let sum = nums[i] + nums[j] + nums[lo] + nums[hi]; if (sum == target) { res.push([nums[i], nums[j], nums[lo], nums[hi]]); temp = nums[lo]; while (lo < hi && temp == nums[lo]) lo++; temp = nums[hi]; while (lo < hi && temp == nums[hi]) hi--; } else if (sum < target) { lo++; } else { hi--; } } } } return res; };