LeetCode-018 4Sum
2017-12-08 21:14
405 查看
Description
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.
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]
]
Analyse
3Sum的升级版,依旧是老套路,不过这次是从遍历一个数变成遍历两个数,依旧是排序,然后两头向中间找和。时间复杂度为O(n3),按照这个规律,其实可以写一个k Sum的代码的,直接递归解决问题,每一层递归都可以将k Sum转换为(k-1) Sum,直到变成2Sum。Code
class Solution { public: vector<vector<int>> fourSum(vector<int>& nums, int target) { set<vector<int>> ans; if (nums.size()<4) return vector<vector<int>> (ans.begin(),ans.end()); sort(nums.begin(),nums.end()); for (int i=0;i<nums.size()-3;i++) 4000 { for (int j=i+1;j<nums.size()-2;j++) { int p=j+1,q=nums.size()-1; while (p<q) { int sum=nums[i]+nums[j]+nums[p]+nums[q]; if (sum==target) { vector<int> temp; temp.push_back(nums[i]); temp.push_back(nums[j]); temp.push_back(nums[p]); temp.push_back(nums[q]); ans.insert(temp); p++; q--; } else { if (sum<target) { p++; } else { q--; } } } } } return vector<vector<int>> (ans.begin(),ans.end()); } };
相关文章推荐
- LeetCode 018 4sum
- [LeetCode]题解(python):018-4Sum
- leetcode 018 4sum (Python)
- 2017-09-10 LeetCode_018 4Sum
- LeetCode 018 4Sum
- LeetCode 018 4Sum
- LeetCode 018 4Sum
- LeetCode--4Sum
- LeetCode题解——4Sum
- LeetCode 4Sum
- LeetCode(18) 4Sum
- 4Sum_leetCode
- leetcode: 4Sum
- [LeetCode] 4Sum
- 4Sum_Leetcode_#18
- LeetCode 18_4Sum
- leetcode--18. 4Sum
- Sum—LeetCode-18 4Sum
- leetcode 18. 4Sum
- [leetcode 17] 4Sum