[Leetcode 48] 18 4 Sum
2013-05-25 10:42
495 查看
Problem:
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.
Analysis:
It's very much like 3 Sum except that we need another variable start from the end of the given array
Code:
View Code
Attention:
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)
Analysis:
It's very much like 3 Sum except that we need another variable start from the end of the given array
Code:
class Solution { public: vector<vector<int> > fourSum(vector<int> &num, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<vector<int> > res; sort(num.begin(), num.end()); int a = 0; while (a < num.size()) { int b = num.size()-1; while (b > a) { int c = a+1, d = b-1; while (c < d) { int sum = num[a] + num[b] + num[c] + num[d]; if (sum == target) { vector<int> tmp; tmp.push_back(num[a]); tmp.push_back(num[c]); tmp.push_back(num[d]); tmp.push_back(num[b]); res.push_back(tmp); do {c++;} while (num[c]==num[c-1] && c < b); do {d--;} while (num[d]==num[d+1] && d > a); } else if ( sum < target) { c++; } else { d--; } } do {b--;} while (num[b] == num[b+1] && b > 0); } do {a++;} while (num[a] == num[a-1] && a < num.size()); } return res; } };
View Code
Attention:
相关文章推荐
- leetcode 18. 4Sum
- python写算法题:leetcode: 18. 4Sum
- 【LeetCode】18. 4Sum (2 solutions)
- 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 K-sum系列
- leetcode 18 -- 4Sum
- [leetcode-18]4Sum(java)
- leetcode18:4Sum
- Sum—LeetCode-18 4Sum
- 个人记录-LeetCode 18. 4Sum
- leetcode解题之 18. 4Sum Java版(结果是目标值的四个数字和)
- LeetCode 18. 4Sum (四数之和)
- leetcode18 4sum