Leetcode-18. 4Sum
来源:互联网 发布:免费oa办公系统源码 编辑:程序博客网 时间:2024/06/02 06:22
题目:
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: 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]
]
思路
可以将4sum转成求3sum,进而转成求2sum,借助set实现无重复解。
代码
class Solution {public: vector<vector<int> > fourSum(vector<int>& nums, int target) { vector<vector<int> > result; if(nums.size() < 4) return result; sort(nums.begin(), nums.end()); set<vector<int> > se; int len = nums.size(); for(int i=0; i<len-3; i++){ for(int j=i+1; j<len-2; j++){ int begin=j+1; int end=len-1; while(begin<end){ int sum=nums[i]+nums[j]+nums[begin]+nums[end]; if(sum == target){ vector<int> temp; temp.push_back(nums[i]); temp.push_back(nums[j]); temp.push_back(nums[begin++]); temp.push_back(nums[end--]); se.insert(temp); }else if(sum < target) begin++; else end--; } } } set<vector<int> >::iterator it; for(it=se.begin(); it!=se.end();it++) result.push_back(*it); return result; }};
0 0
- LeetCode --- 18. 4Sum
- [Leetcode] 18. 4Sum
- leetcode 18. 4Sum
- 18. 4Sum LeetCode
- leetcode 18. 4Sum
- 【LeetCode】18. 4Sum
- LeetCode - 18. 4Sum
- leetcode 18. 4Sum
- Leetcode 18. 4Sum
- LeetCode 18. 4Sum
- 【leetcode】18. 4Sum
- leetcode 18. 4Sum
- [leetcode]18. 4Sum
- leetcode 18. 4Sum
- leetcode 18. 4Sum
- leetcode 18. 4Sum
- [LeetCode] 18. 4Sum
- LeetCode 18. 4Sum
- Python 内置的object对象(1)
- CDOJ 1402 三角形棋盘上的博弈游戏 状压DP
- 【深度学习基础】机器学习的定义与demo展示
- 解说Win32的窗口子类化
- 12-jQuery各版本增加的一些方法
- Leetcode-18. 4Sum
- ummm
- 【天梯赛】L2-011. 玩转二叉树 ( 层次遍历 )
- POJ
- 13-jQuery性能优化
- Tomcat/Weblogic/Websphere 我们选择哪一个
- Linux下查看支持的信号列表
- mac上设置VS Code---------支持ejs
- 13、安装jdk的虚拟机centos6.8简单安装部署tomcat8