leetcode 第18题 4Sum
2015-04-26 09:54
316 查看
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:
思路:与 2Sum解决方法类似,两个指针一个在前,一个在后。
代码实现:
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)
思路:与 2Sum解决方法类似,两个指针一个在前,一个在后。
代码实现:
class Solution { public: vector<vector<int> > fourSum(vector<int> &num, int target) { vector<vector<int>> res; set<vector<int>> tepres; int len = num.size(); if(len < 4) return res; sort(num.begin(),num.end()); for(int i = 0; i < len;i++){ for(int j = i+1;j<len;j++){ int begin = j + 1; int end = len - 1; while(begin < end){ int sum = num[i] + num[j] + num[begin] + num[end]; if(sum == target){ vector<int> tep; tep.push_back(num[i]); tep.push_back(num[j]); tep.push_back(num[begin]); tep.push_back(num[end]); tepres.insert(tep); begin++; end--; } else if(sum < target) begin++; else end--; } } } set<vector<int>>::iterator it = tepres.begin(); for(;it != tepres.end();it++){ res.push_back(*it); } return res; } };
相关文章推荐
- 【LeetCode】LeetCode——第18题:4Sum
- LeetCode第18题之4Sum
- *LeetCode-4Sum
- [leetcode]18. 4Sum
- 4Sum -- leetcode
- 和大神们学习每天一题(leetcode)-4Sum
- 4Sum--LeetCode
- 算法分析与设计课程(17):【leetcode】4Sum
- leetcode: 4Sum
- Leetcode 18 : 4sum
- LeetCode 4Sum
- leetcode 4sum
- LeetCode 18 4Sum
- Leetcode 18. 4Sum
- 【Leetcode】4Sum
- 【Leetcode】C# 18、4Sum
- leetcode: 4Sum
- leetcode: 4Sum
- [LeetCode] 4Sum
- leetcode - 4Sum