[Leetcode 48] 18 4 Sum
Problem:
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)
Analysis:
It's very much like 3 Sum except that we need another variable start from the end of the given array
Code:
1 class Solution { 2 public: 3 vector<vector<int> > fourSum(vector<int> &num, int target) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 vector<vector<int> > res; 7 8 sort(num.begin(), num.end()); 9 10 int a = 0; 11 while (a < num.size()) { 12 int b = num.size()-1; 13 while (b > a) { 14 int c = a+1, d = b-1; 15 16 while (c < d) { 17 int sum = num[a] + num[b] + num[c] + num[d]; 18 19 if (sum == target) { 20 vector<int> tmp; 21 tmp.push_back(num[a]); 22 tmp.push_back(num[c]); 23 tmp.push_back(num[d]); 24 tmp.push_back(num[b]); 25 26 res.push_back(tmp); 27 28 do {c++;} while (num[c]==num[c-1] && c < b); 29 do {d--;} while (num[d]==num[d+1] && d > a); 30 } else if ( sum < target) { 31 c++; 32 } else { 33 d--; 34 } 35 } 36 37 do {b--;} while (num[b] == num[b+1] && b > 0); 38 } 39 40 do {a++;} while (num[a] == num[a-1] && a < num.size()); 41 } 42 43 return res; 44 } 45 };
Attention: