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)
思路:找出四个元素,其和为制定元素的值,首先定义一个函数,来找出所有符合这一条件的方法。首先定义前两个相邻的索引,然后在定义一个这两个元素其后的头指针begin,最后定义一个尾指针end。如果target小于这四个数之和,则begin++;如果大于这四个数之和,则end--;如果相等呢,则将这四个数放入path数组中,最后放入allpaths,最后下一循环begin++;主函数里就可以围绕相邻两个元素的索引变换了,最后将这个allpaths中重复的元素去掉。
class Solution { public: void findFourSum(vector<int> &num,int target,int first,int second,vector<vector<int> > &allpaths) { target=target-num[first]-num[second]; int begin=second+1; int end=num.size()-1; while(begin<end) { int sum=num[begin]+num[end]; if(sum>target) end--; else if(sum<target) begin++; else { vector<int> path(4); path[0]=num[first]; path[1]=num[second]; path[2]=num[begin]; path[3]=num[end]; allpaths.push_back(path); begin++; } } } vector<vector<int> > fourSum(vector<int> &num, int target) { vector<vector<int> > result; result.clear(); if(num.size()<4) return result; sort(num.begin(),num.end()); vector<vector<int> > allpaths; allpaths.clear(); for(int i=0;i<num.size()-3;i++) { for(int j=i+1;j<num.size()-2;j++) { findFourSum(num,target,i,j,allpaths); } } for(int i=0;i<allpaths.size();i++) { if(find(result.begin(),result.end(),allpaths[i])==result.end()) result.push_back(allpaths[i]); } return result; } };