18. 4Sum
2016-01-08 20:32
295 查看
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.
此题和3sum思路基本相同,不同的是,需要固定两个数,而不是一个数,而且要求4个数的和是target而不是0。
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)
此题和3sum思路基本相同,不同的是,需要固定两个数,而不是一个数,而且要求4个数的和是target而不是0。
class Solution { private: vector<vector<int>> result; public: vector<vector<int>> fourSum(vector<int>& nums, int target) { if(nums.size()<4) return result; sort(nums.begin(),nums.end()); vector<int> temp(4); for(int i=0;i<nums.size()-3;i++){ if(i!=0&&nums[i]==nums[i-1]) continue; for(int j=i+1;j<nums.size()-2;j++){ if(j!=i+1&&nums[j]==nums[j-1]) continue; int left=j+1; int right=nums.size()-1; while(left<right){ int sum=nums[i]+nums[j]+nums[left]+nums[right]; if(sum==target){ temp[0]=nums[i]; temp[1]=nums[j]; temp[2]=nums[left]; temp[3]=nums[right]; result.push_back(temp); left++; right--; while(left<right&&nums[left]==nums[left-1]) left++; while(left<right&&nums[right]==nums[right+1]) right--; } else if(sum>target) right--; else left++; } } } return result; } };
相关文章推荐
- 3. Twitter的客户端框架——Bootstrap
- myeclipse与数据库进行连接(无需写代码进行验证)
- 傅里叶变换的通俗解释—转载
- wyx
- 层次分析法(AHP)的Matlab实现
- 嵌入式
- 【慕课笔记】第二章 变量和常量 第2节 认识JAVA标识符
- Security 可视化
- struts2配置内置校验器
- 建立nfs共享
- 【带偏移量的并查集】:poj2492,A Bug's Life
- 第一组咖啡机器人部分图形设计
- 15.3sum
- 安卓修炼之路必要要知道的要求和建议
- 安卓修炼之路必要要知道的要求和建议
- svn *.so 文件上传
- 安卓修炼之路必要要知道的要求和建议
- 给你的iOS应用更换主题
- js动画--缓冲动画
- 快速(Storyboard/模型思想搭建设置页面)(二)