4Sum
2016-07-14 19:32
477 查看
题目描述:
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.
解题思路:
类似于题目3Sum,不同之处是这里需要固定两个数字,3Sum的解题思路可以参考:3Sum
AC代码如下:
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> res;
int numlen = nums.size();
if (nums.size()<4) return res;
sort(nums.begin(), nums.end());
for (int i = 0; i < numlen; i++)
{
if (i != 0 && nums[i] == nums[i - 1]) continue; //跳过重复的元素,避免结果中出现重复的四元组
for (int j = i + 1; j < numlen; j++)
{
if (j != i + 1 && nums[j] == nums[j - 1]) continue; //跳过重复的元素,避免结果中出现重复的四元组
int begin = j + 1;
int end = numlen - 1;
while (begin < end)
{
int sum = nums[i] + nums[j] + nums[begin] + nums[end];
if (sum == target)
{
vector<int> tmp = {nums[i],nums[j],nums[begin],nums[end]};
res.push_back(tmp);
while (++begin<end && nums[begin] == nums[begin - 1]); //跳过重复的元素,避免结果中出现重复的四元组
while (--end>begin && nums[end] == nums[end + 1]); //跳过重复的元素,避免结果中出现重复的四元组
}
else if (sum<target)
begin++;
else
end--;
}
}
}
return res;
}
};
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] ]
解题思路:
类似于题目3Sum,不同之处是这里需要固定两个数字,3Sum的解题思路可以参考:3Sum
AC代码如下:
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> res;
int numlen = nums.size();
if (nums.size()<4) return res;
sort(nums.begin(), nums.end());
for (int i = 0; i < numlen; i++)
{
if (i != 0 && nums[i] == nums[i - 1]) continue; //跳过重复的元素,避免结果中出现重复的四元组
for (int j = i + 1; j < numlen; j++)
{
if (j != i + 1 && nums[j] == nums[j - 1]) continue; //跳过重复的元素,避免结果中出现重复的四元组
int begin = j + 1;
int end = numlen - 1;
while (begin < end)
{
int sum = nums[i] + nums[j] + nums[begin] + nums[end];
if (sum == target)
{
vector<int> tmp = {nums[i],nums[j],nums[begin],nums[end]};
res.push_back(tmp);
while (++begin<end && nums[begin] == nums[begin - 1]); //跳过重复的元素,避免结果中出现重复的四元组
while (--end>begin && nums[end] == nums[end + 1]); //跳过重复的元素,避免结果中出现重复的四元组
}
else if (sum<target)
begin++;
else
end--;
}
}
}
return res;
}
};
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C++的template模板中class与typename关键字的区别分析
- C与C++之间相互调用实例方法讲解