难度:Medium
题目链接:https://leetcode.com/problems/4sum
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums 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 nums = [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]
]
思路和 3Sum 类似,多了一层for循环。为了避免重复,在存储结果的时候使用STL的set。
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
if (nums.size() < 4) return vector<vector<int>>{};
std::set<vector<int>> res;
std::sort(nums.begin(), nums.end());
for (size_t i = 0; i < nums.size() - 3; ++i)
for (size_t j = i + 1; j < nums.size() - 2; ++j) {
auto left_idx = j + 1; auto right_idx = nums.size() - 1;
int sum = 0;
for (left_idx = j + 1, right_idx = nums.size() - 1; left_idx < right_idx; sum > target ? --right_idx : ++left_idx) {
sum = nums[i] + nums[j] + nums[left_idx] + nums[right_idx];
if (sum == target) {
vector<int> res_single{nums[i], nums[j], nums[left_idx], nums[right_idx]};
res.insert(res_single);
}
}
}
return vector<vector<int>>(res.begin(), res.end());
}
};