Problem: given an arraySOfNIntegers, are there elementsA,B,C, AndDInSSuch thatA+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)
This question is actually a variant of the past. I think so. First, we should sort it well, and then fix the four headers and tails, that is, I is the header, starting from 0 to the fourth to last, J is the tail starting from the end to I + 2. another left = I + 1 Right = J-1 if I + + is equal to the previous one, then directly continue, because it has been calculated in the previous I, similarly, J -- if it is equal to the previous J, then it does not need to calculate the direct continue. In this case, the complexity is N3.
class Solution {public:vector<vector<int> > fourSum(vector<int> &num, int target){ vector<vector<int> > sum; sum.clear(); if(num.size() < 4) return sum; sort(num.begin(), num.end()); for (int i = 0; i < num.size() - 3; ++i) { if (i - 1 >=0 && num[i - 1] == num[i]) continue; for (int j = num.size() - 1; j > i + 2; --j) { if(j + 1 < num.size() && num[j + 1] == num[j]) continue; int left = i + 1, right = j - 1; while(left < right) { if (num[i] + num[left] + num[right] + num[j] == target) { if(sum.size()==0 || sum.size()>0 && !(sum[sum.size() - 1][0]==num[i] && sum[sum.size() - 1][1]==num[left] && sum[sum.size() - 1][2]==num[right])) { vector<int> tep; tep.push_back(num[i]); tep.push_back(num[left]); tep.push_back(num[right]); tep.push_back(num[j]); sum.push_back(tep); } left++; right--; } else if (num[i] + num[left] + num[right] + num[j] < target) left++; else if (num[i] + num[left] + num[right] + num[j] > target) right--; } } } return sum;}};
Leetcode 17th -- 4Sum