題目
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:
Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
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)
解題之法
// O(n^3)
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &nums, int target) {
set<vector<int> > res;
sort(nums.begin(), nums.end());
for (int i = 0; i < int(nums.size() - 3); ++i) {
for (int j = i + 1; j < int(nums.size() - 2); ++j) {
int left = j + 1, right = nums.size() - 1;
while (left < right) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum == target) {
vector<int> out;
out.push_back(nums[i]);
out.push_back(nums[j]);
out.push_back(nums[left]);
out.push_back(nums[right]);
res.insert(out);
++left; --right;
} else if (sum < target) ++left;
else --right;
}
}
}
return vector<vector<int> > (res.begin(), res.end());
}
};
分析
LeetCode中關(guān)于數(shù)字之和還有其他幾道,分別是Two Sum 兩數(shù)之和,3Sum 三數(shù)之和,3Sum Closest 最近三數(shù)之和,雖然難度在遞增,但是整體的套路都是一樣的,在這里為了避免重復(fù)項(xiàng),我們使用了STL中的set,其特點(diǎn)是不能有重復(fù),如果新加入的數(shù)在set中原本就存在的話,插入操作就會(huì)失敗,這樣能很好的避免的重復(fù)項(xiàng)的存在。此題的O(n^3)解法的思路跟3Sum 三數(shù)之和基本沒(méi)啥區(qū)別,就是多加了一層for循環(huán),其他的都一樣。