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)
Extended from 3Sum, fixed the first pointer, and for the last three pointers, solve the problem use 3Sum.
Solution:
This problem can be downgraded to 3Sum then to 2Sum problem. We will solve the most inner loop using two pointers. For all other loops, we linearly scanning over the given array. The trick here is that in each loop, we skip over identical elements which are not seen the first time.
This problem can be downgraded to 3Sum then to 2Sum problem. We will solve the most inner loop using two pointers. For all other loops, we linearly scanning over the given array. The trick here is that in each loop, we skip over identical elements which are not seen the first time.
No comments:
Post a Comment