class Solution {
//fix i, j, then let p q walk to find out the fourSum target O(n^3)
//there exists O(n^2logn) solution
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(num.size() < 4) return vector<vector<int> >();
sort(num.begin(), num.end());
vector<vector<int>> ans;
for (int i = 0; i < num.size()-3; ++i)
{
for (int j = i+1; j < num.size()-2; ++j)
{
int p = j+1; int q = num.size()-1;
fourSum_aux(num, target, i, j, p, q, ans);
}
}
return ans;
}
void fourSum_aux( const vector<int> & num, int target, int i, int j, int p, int q,
vector<vector<int>>& ans )
{
//throw std::exception("The method or operation is not implemented.");
target = target-num[i]-num[j];
while (p < q)
{
int sum = num[p]+num[q];
if(sum > target)
q--;
else if (sum < target)
p++;
else
{
vector<int> path(4);
path[0] = num[i]; path[1] = num[j]; path[2] = num[p]; path[3] = num[q];
p++;
if ( find(ans.begin(), ans.end(), path) == ans.end() )//...
ans.push_back(path);
}
}
}
};
second time
class Solution {
public:
void fourSumUtil(vector<int>& num, int target, int firstIdx, int secondIdx, vector<vector<int> >& allPath)
{
target = target-num[firstIdx]-num[secondIdx];
int left = secondIdx+1;
int right = num.size()-1;
while(left < right)
{
int sum = num[left]+num[right];
if(sum < target) left++;
else if(sum > target) right--;
else
{
vector<int> path(4);
path[0] = num[firstIdx]; path[1] = num[secondIdx]; path[2] = num[left]; path[3] = num[right];
allPath.push_back(path);
left++;
}
}
}
vector<vector<int> > fourSum(vector<int> &num, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
sort(num.begin(), num.end());
vector<vector<int> > allPaths;
for(int i = 0; i < (int)num.size()-3; ++i)
{
for(int j = i+1; j < (int)num.size()-2; ++j)
{
fourSumUtil(num, target, i, j, allPaths);
}
}
//abort duplicates
vector<vector<int> > ans;
for(int i = 0; i < allPaths.size(); ++i)
if(find(ans.begin(), ans.end(), allPaths[i]) == ans.end()) ans.push_back(allPaths[i]);
return ans;
}
};