18. 4Sum
Last updated
Was this helpful?
Last updated
Was this helpful?
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.
Thoughts:
Naive way: break down problems into -> ; In general: for sum, use recursion to break down to (k-1)->(k-2) until reaching 2, which is solved using the algorithm for two Sum
Since we need ALL solutions, tricks for removing duplicates, as adopted in is also adopted.
When k > 2, I prefer using two pointers as the time complexities is no longer dominant by sorting (O(nlogn)).
Special thanks: for the reference!