[LeetCode] 4Sum

[Problem]

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)
[Analysis]
对数组进行排序,使用4个指针,先固定前面前面两个,然后对后面两个使用两边夹逼的方法。例如,对于上面的例子,排序后S = {-2 -1 0 0 1 2},先固定-2 -1,然后后面连个指针指向0和2,此时的sum=(-2)+(-1)+(0)+(2)=-1,比target小,则第3个指针+1,此时的sum=(-2)+(-1)+(0)+(2)=-1,sum<target,继续移动第3个指针,sum=(-2)+(-1)+(1)+(2)=0,sum==target,保存结果,第3个指针和第4个指针互相靠拢。
此过程中注意剪枝,移动指针的时候,如果移动后的指针指向的数和移动前指向的数相同,则可以直接跳过。

[Solution]

class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int i = 0, j = 0, k = 0, l = 0, m = 0;
vector<vector<int> > res;
if(num.size() < 4)
return res;

// not null
sort(num.begin(), num.end());
while(i <= num.size() - 4){
// the first number is bigger than 0
//if(num[i] > target)break;

// add the second number
j = i + 1;
while(j <= num.size() - 3){
// the sum of the first two number is bigger than 0
//if(num[i] + num[j] > target)break;

// add the third number
k = j + 1;
l = num.size() - 1;
while(l > k){
// the sum of the four number equals to 0, add to result
int sum = num[i] + num[j] + num[k] + num[l];
if(sum == target){
vector<int> tmp;
tmp.push_back(num[i]);
tmp.push_back(num[j]);
tmp.push_back(num[k]);
tmp.push_back(num[l]);
res.push_back(tmp);

// move forward for the same num[l]
m = num[l];
l--;
while(l > k && num[l] == m){
l--;
}

// move forward for the same num[k]
m = num[k];
k++;
while(k < l && num[k] == m){
k++;
}
}
else if(sum > target){
// move forward for the same num[l]
m = num[l];
l--;
while(l > k && num[l] == m){
l--;
}
}
else{
// move forward for same num[k]
m = num[k];
k++;
while(k < l && num[k] == m){
k++;
}
}
}

// move forward for same num[j]
m = num[j];
j++;
while(j <= num.size() - 3 && num[j] == m){
j++;
}
}

// move forward for same num[i]
m = num[i];
i++;
while(i <= num.size() - 4 && num[i] == m){
i++;
}
}
return res;
}
};


说明:版权所有,转载请注明出处。 Coder007的博客
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值