LeetCode——4Sum
1. Question
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.
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]
]
2. Solution
这个问题的解法和3sum一样,只不过现在是4个数求和了,先遍历所有两个数字的组合,然后在去找另外两个数,时间复杂度为O(n^3)。
3. Code
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
if (nums.size() <= 3)
return vector<vector<int>>();
sort(nums.begin(), nums.end());
vector<vector<int>> res;
for (int i = 0; i < nums.size() - 3; i++) {
for (int j = i + 1; j < nums.size() - 2; j++) {
int start = j + 1;
int end = nums.size() - 1;
int tmp_target = target - (nums[i] + nums[j]);
while (start < end) {
int tmp = nums[start] + nums[end];
if (tmp > tmp_target)
end--;
else if (tmp < tmp_target)
start++;
else {
vector<int> result;
result.push_back(nums[i]);
result.push_back(nums[j]);
result.push_back(nums[start]);
result.push_back(nums[end]);
res.push_back(result);
// 去掉start开始重复的
while (start < end && nums[start] == result[2])
start++;
// 去掉end开始重复的
while (end > start && nums[end] == result[3])
end--;
}
}
// 去掉重复的第二个数
while (j + 1 < nums.size() - 2 && nums[j + 1] == nums[j])
j++;
}
// 去掉重复的第一个数
while (i + 1 < nums.size() - 3 && nums[i + 1] == nums[i])
i++;
}
return res;
}
};