leetcode[18]4Sum
2015-02-10 13:39
387 查看
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.
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)
class Solution { public: vector<vector<int>> fourSum(vector<int> &num, int target) { vector<vector<int>> res; if(num.size()<4)return res; sort(num.begin(),num.end()); int c,d; for(int a=0;a<num.size();a++) { if(a>0&&num[a]==num[a-1]) continue; for(int b=a+1;b<num.size();b++) { if(b>a+1&&num[b]==num[b-1]) continue; c=b+1; d=num.size()-1; while(c<d) { if(c>b+1&&num[c]==num[c-1]) { c++; continue; } if(d<num.size()-1&&num[d]==num[d+1]) { d--; continue; } int sum=num[a]+num[b]+num[c]+num[d]; if(sum<target)c++; else if(sum>target)d--; else { vector<int> temp; temp.push_back(num[a]); temp.push_back(num[b]); temp.push_back(num[c]); temp.push_back(num[d]); res.push_back(temp); c++; d--; } } } } return res; } };
相关文章推荐
- [leetcode]18. 4Sum
- 【leetcode】18. 4Sum
- leetcode 18. 4Sum
- leetcode 18 4Sum
- LeetCode - 18 - 4Sum
- LeetCode18:4Sum
- leetcode 18. 4Sum
- LeetCode *** 18. 4Sum (Two Pointers)
- LeetCode 18. 4Sum
- LeetCode 18 4Sum
- LeetCode之18_4Sum
- leetcode-18-4Sum
- leetcode.array--18. 4Sum
- LeetCode 18. 4Sum
- LeetCode 18 - 4Sum
- LeetCode 18. 4Sum
- [LeetCode] 18. 4Sum
- 【LeetCode】18. 4Sum
- LeetCode 18: 4Sum
- leetcode 18. 4Sum