一、3Sum
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
思路:给定一个数组arr[n] 在arr[0]:arr[n-1]这n个元素中,每次先固定一个元素a,然后再剩下的元素中找b、c,使得a+b+c=0
但是有一个问题 如何消除重复的三元组,(Output Limit Exceeded多是由于重复结果引起的)
设结果三元组为(a,b,c)
先排序
对于第一个元素a来说,在向后移动的过程中,只要不和前一个元素一样就可以继续。
对于b来说,它不能和(a,b)区间内b的前一个数字相等
对于c来说,它不能喝(c,n-1)区间内c的后一个数字相等
这样就能保证无重复
对于4sum以上的求和
sort(res.begin(),res.end());
res.erase(unique(res.begin()),res.end());
下面是代码:
vector<vector<int> > threeSum(vector<int> &num)
{
vector<vector<int>> res;
if(num.size()<3)
return res;
sort(num.begin(),num.end());
for(int i=0;i<num.size();i++)
{
if(i>0&&num[i]==num[i-1])//消除冗余
continue;
int a=num[i];
int l=i+1;
int r=num.size()-1;
while(l<r)
{
if(l>i+1&&num[l]==num[l-1]){//消除冗余
l++;
continue;
}
if(r<num.size()-1&&num[r]==num[r+1])//消除冗余
{
r--;
continue;
}
if(num[l]+num[r]+a<0)
l++;
else if(num[l]+num[r]+a>0)
r--;
else
{
vector<int>tmp;
tmp.push_back(num[i]);
tmp.push_back(num[l]);
tmp.push_back(num[r]);
res.push_back(tmp);
l++;
}
}
}
return res;
}
二、
4Sum
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)
思路与3sum类似 关键还是处理重复的四元组
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
vector<vector<int>> res;
if(num.size()<4)
return res;
// int i=0;
//int j=num.size()-1;
sort(num.begin(),num.end());
for(int i=0;i<num.size();i++)
{
if(i>0&&num[i]==num[i-1])//
continue;
for(int j=i+1;j<num.size();j++)
{
if(j>i+1&&num[j]==num[j-1])//
continue;
int l=j+1;
int r=num.size()-1;
while(l<r)
{
if(l>j+1&&num[l]==num[l-1])//
{
l++;
continue;
}
if(r<num.size()-1&&num[r]==num[r+1])//
{
r--;
continue;
}
int sum=num[i]+num[j]+num[l]+num[r];
if(sum<target)
{
l++;
}
else if(sum>target)
{
r--;
}
else
{
vector<int> tmp;
tmp.push_back(num[i]);
tmp.push_back(num[j]);
tmp.push_back(num[l]);
tmp.push_back(num[r]);
res.push_back(tmp);
l++;
}
}
}
}
//sort(res.begin(),res.end());
//res.erase(unique(res.begin(),res.end()),res.end());
return res;
}
};</span>
注释标注的就是消除重复的代码,可以发现xSum,就有x条消除冗余的代码!