[Leetcode] 4Sum
阿新 • • 發佈:2018-01-27
element com target https tor 方法 nta body 文章
4Sum 題解
原創文章,拒絕轉載
題目來源:https://leetcode.com/problems/4sum/description/
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
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]
]
Solution
class Solution {
private:
vector<vector<int> > twoSum(vector<int>& nums, int end, int target) {
vector<vector<int > > res;
int low = 0;
int high = end;
while (low < high) {
if (nums[low] + nums[high] == target) {
vector<int> sum(2);
sum[0] = nums[low++];
sum[1] = nums[high--];
res.push_back(sum);
// 去重
while (low < high && nums[low] == nums[low - 1])
low++;
while (low < high && nums[high] == nums[high + 1])
high--;
} else if (nums[low] + nums[high] > target) {
high--;
} else {
low++;
}
}
return res;
}
vector<vector<int> > threeSum(vector<int>& nums, int end, int target) {
vector<vector<int>> res;
if (end < 2)
return res;
sort(nums.begin(), nums.end());
for (int i = end; i >= 2; i--) {
if (i < end && nums[i] == nums[i + 1]) // 去重
continue;
auto sum2 = twoSum(nums, i - 1, target - nums[i]);
if (!sum2.empty()) {
for (auto& sum : sum2) {
sum.push_back(nums[i]);
res.push_back(sum);
}
}
}
return res;
}
public:
vector<vector<int> > fourSum(vector<int>& nums, int target) {
vector<vector<int>> res;
int size = nums.size();
if (size < 4)
return res;
sort(nums.begin(), nums.end());
for (int i = size - 1; i >= 2; i--) {
if (i < size - 1 && nums[i] == nums[i + 1]) // 去重
continue;
auto sum3 = threeSum(nums, i - 1, target - nums[i]);
if (!sum3.empty()) {
for (auto& sum : sum3) {
sum.push_back(nums[i]);
res.push_back(sum);
}
}
}
return res;
}
};
解題描述
這道題可以說是3Sum的再次進階,使用的方法和3Sum基本相同,只是在求3個數之和之後再套上一層循環。時間復雜度為O(n^3)。
[Leetcode] 4Sum