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:
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)
和sum3 差不多,枚举a ,b 再 解 c+d 的定值的问题。
写的时候漏了一些小地方, continue 之前要 改变p,q .
class Solution { private: vector<vector<int> > ret; public: vector<vector<int> > fourSum(vector<int> &num, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function ret.clear(); sort(num.begin(),num.end()); for(int i = 0; i < num.size() ; i++) { if( i > 0 && num[i] == num[i-1]) continue; for( int j = i+1; j < num.size() ; j++) { if( j > i+1 && num[j]==num[j-1]) continue; int p = j + 1; int q = num.size() -1; while( p < q) { if( p > j + 1 && num[p] == num[p-1]) { p++; continue; } if( q < num.size() -1 && num[q] == num[q+1]) { q--; continue; } int sum = num[i] + num[j] + num[p] + num[q]; if(sum==target) { vector<int> tmp; tmp.push_back(num[i]); tmp.push_back(num[j]); tmp.push_back(num[p]); tmp.push_back(num[q]); ret.push_back(tmp); p++; }else if(sum > target) { q--; }else { p++; } } } } return ret; } };