首页 > 代码库 > 4Sum
4Sum
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:
- 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)
思路:找出四个元素,其和为制定元素的值,首先定义一个函数,来找出所有符合这一条件的方法。首先定义前两个相邻的索引,然后在定义一个这两个元素其后的头指针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; } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。