Given an array
nums
of n integers and an integer target
, are there elements a, b, c, and d in nums
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.
Example:
Given array nums = [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 = nums.sort();
const result = [];
const n = nums.length;
let l;
for(let i=0; i<n-3; i++) {
for(let j=i+1; j<n-2; j++) {
for(let k=j+1; k<n-1; k++) {
for(let l=k+1; l<n; l++) {
if (nums[i]+nums[j]+nums[k]+nums[l] === target) {
result.push([nums[i], nums[j], nums[k], nums[l]])
}
}
}
}
}
return Array.from(new Set(result.map(JSON.stringify))).map(JSON.parse);
};
console.log(fourSum([-5,5,4,-3,0,0,4,-2], 4));
Run the code here: https://repl.it/@VinitKhandelwal/18-foursum-leetcode
Comments
Post a Comment