https://oj.leetcode.com/problems/4sum/
在一个数列中,找出所有的4个数,它们的和是target.
class Solution { public: vector<vector<int> > fourSum(vector<int> &num, int target) { vector<vector<int> > ans; if(num.size()<4) return ans; sort(num.begin(),num.end()); for(int i = 0;i<num.size()-3;i++) { if(i>0 && num[i]==num[i-1]) continue; calcThree(num,target - num[i],i,ans); } return ans; } void calcThree(vector<int> &num,int threeSum,int firstPosition,vector<vector<int> > &ans) { int k = 0; for(int i = firstPosition+1;i<num.size()-2;i++) { if(i>firstPosition+1 && num[i] == num[i-1]) continue; int j = i+1; k = num.size()-1; while(j<k) { if(num[i]+num[j]+num[k] == threeSum) { if(ans.size()==0 || ans.size()>0 && !(num[firstPosition] == ans[ans.size()-1][0] && num[i]==ans[ans.size()-1][1]&& num[j] ==ans[ans.size()-1][2] )) { vector<int> ansPiece; ansPiece.push_back(num[firstPosition]); ansPiece.push_back(num[i]); ansPiece.push_back(num[j]); ansPiece.push_back(num[k]); ans.push_back(ansPiece); } j++; } else if(num[i]+num[j]+num[k] < threeSum) j++; else k--; } } } };