您的位置:首页 > 其它

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());
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: