18. 4Sum
2018-01-11 09:43
176 查看
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.
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] ]
class Solution { public: void Sum4_helper_helper(vector<int> &nums,int begin,int end,int target,int first,int second,vector<vector<int>> &result) { int low=begin,high=end; while(low<high) { if(high-low+1==2) { if(nums[low]+nums[high]==target) { vector<int> tmp; tmp.push_back(first); tmp.push_back(second); tmp.push_back(nums[low]); tmp.push_back(nums[high]); result.push_back(tmp); } return; } if(nums[low]+nums[high]>target) high--; else if(nums[low]+nums[high]<target) low++; else { if((low<end)&&(nums[low]==nums[low+1])) { low++; continue; } if (high>begin&&(nums[high]==nums[high-1])) { high--; continue; } vector<int> tmp; tmp.push_back(first); tmp.push_back(second); tmp.push_back(nums[low]); tmp.push_back(nums[high]); result.push_back(tmp); low++; } } } void Sum4_helper(vector<int> &nums,int begin,int end,int target,int first,vector<vector<int>> &result) { for (int i=begin; i<=end;){ int t=target-nums[i]; Sum4_helper_helper(nums, i+1, end, t,first,nums[i],result); int tmp=nums[i]; while(tmp==nums[i]) i++; } } vector<vector<int>> fourSum(vector<int> &nums,int target) { vector<vector<int>> result; if(nums.size()<4) return result; sort(nums.begin(),nums.end()); for (int i=0; i<nums.size()-3;) { int t=target-nums[i]; Sum4_helper(nums, i+1, nums.size()-1, t,nums[i],result); int tmp=nums[i]; while(tmp==nums[i]&&i<nums.size()-3) i++; } return result; } };
相关文章推荐
- LeetCode 18. 4Sum
- LeetCode 18. 4Sum
- leetcode 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- LeetCode 18 - 4Sum
- LeetCode 18_4Sum
- 18. 4Sum
- leetcode 18. 4Sum
- 18. 4Sum
- leetcode -18 4Sum
- 1. Two Sum && 167. Two Sum II - Input array is sorted && 15. 3Sum && 16. 3Sum Closest && 18. 4Sum
- LeetCode (18)4Sum
- 18. 4Sum
- leetcode--18. 4Sum
- Leetcode题解-18. 4Sum
- leetcode 18. 4Sum
- leetCode#18. 4Sum
- [Leetcode] 18. 4Sum
- Leetcode[18]-4Sum