最近较忙,没怎么写LeetCode以后尽量保证每天一道题目以上。
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)
最近忙别的事情,看不懂代码的直接邮箱联系yuluoyzw@gmail.com.
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> rsvv;
if (nums.size()<4)
return rsvv;
vector<int> temp(4, 0);
sort(nums.begin(), nums.end());
int size = nums.size();
for (int i = 0; i<size - 3; i++)
for (int j = i + 1; j<size- 2; j++)
{
int m = j + 1, n = size - 1;
while (m<n)
{
int sum = nums[i] + nums[j] + nums[m] + nums[n];
if (sum<target)
m++;
else if (sum>target)
n--;
else{
temp[0] = nums[i];
temp[1] = nums[j];
temp[2] = nums[m];
temp[3] = nums[n];
//if (!(rsvv.size()>0 && rsvv[rsvv.size() - 1][0] == temp[0] && rsvv[rsvv.size() - 1][1] == temp[1]
//&& rsvv[rsvv.size() - 1][2] == temp[2] && rsvv[rsvv.size() - 1][3] == temp[3]))
//rsvv.push_back(temp);
if (!((j > i + 1 && nums[j] == nums[j - 1]) || (m > j + 1 && nums[m] == nums[m - 1]) || i > 0 && nums[i] == nums[i - 1]))
{
rsvv.push_back(temp);
}
m++;
}
}
}
return rsvv;
}
};