您的位置:首页 > 其它

[Leetcode 48] 18 4 Sum

2013-05-25 10:42 495 查看
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:

It's very much like 3 Sum except that we need another variable start from the end of the given array

Code:

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
vector<vector<int> > res;

sort(num.begin(), num.end());

int a = 0;
while (a < num.size()) {
int b = num.size()-1;
while (b > a) {
int c = a+1, d = b-1;

while (c < d) {
int sum = num[a] + num[b] + num[c] + num[d];

if (sum == target) {
vector<int> tmp;
tmp.push_back(num[a]);
tmp.push_back(num[c]);
tmp.push_back(num[d]);
tmp.push_back(num[b]);

res.push_back(tmp);

do {c++;} while (num[c]==num[c-1] && c < b);
do {d--;} while (num[d]==num[d+1] && d > a);
} else if ( sum < target) {
c++;
} else {
d--;
}
}

do {b--;} while (num[b] == num[b+1] && b > 0);
}

do {a++;} while (num[a] == num[a-1] && a < num.size());
}

return res;
}
};


View Code

Attention:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: