LeetCode18 4Sum

题意:

Given an array S of n integers, are there elements abc, 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.(Medium)

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]
]

分析:

还是采取跟2sum,3sum一样的思路,先排序,再two pointers.

实现的时候利用3sum,然后加一层循环,复杂度O(n^3).

代码:

 class Solution {
private:
vector<vector<int>> threeSum(vector<int>& nums, int target) {
vector<vector<int>> v;
if (nums.size() < ) { //数组元素个数过少,直接返回
return v;
}
for (int i = ; i < nums.size() - ; ++i) {
if (i >= && nums[i] == nums[i - ]) {
continue;
}
int start = i + , end = nums.size() - ;
while (start < end) {
if ( nums[i] + nums[start] + nums[end] == target ) {
vector<int> temp{nums[i], nums[start], nums[end]};
v.push_back(temp);
start++;
end--;
while ( (start < end) && nums[start] == nums[start - ]) { //没加start < end虽然过了,估计是样例不够完善
start++;
}
while ( (start < end) && nums[end] == nums[end + ]) {
end--;
}
}
else if (nums[i] + nums[start] + nums[end] > target ) {
end--;
}
else {
start++;
}
}
}
return v;
}
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
vector<vector<int>> v;
for (int i = ; i < nums.size(); ++i) {
if (i > && nums[i] == nums[i - ]) {
continue;
}
vector<int> temp(nums.begin() + i + , nums.end());
vector<vector<int>> result = threeSum(temp, target - nums[i]);
for (int j = ; j < result.size(); ++j) {
result[j].push_back(nums[i]);
v.push_back(result[j]);
}
}
return v;
}
};
上一篇:读懂《HTML5网页开发实例详解》这本书


下一篇:SharePoint2010 Form验证配置流程