#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
/*
Given an array S of n integers, are there elements a, b, c and d such that
a + b + c +d = target ?
Find all unique quadruplets in the array which gives the sum of target.
Note:
1: Elements in quadruplet(a, b, c d) must be in non-descending order (ie, a <= b <= c <= d)
2: 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}
*/
// Time Complexity O(N^3)
vector< vector<int> > FourSum(vector<int>& nums, int target) {
if(nums.size() < 4) return {};
vector< vector<int> > res;
sort(nums.begin(), nums.end());
for(int i = 0; i < nums.size() - 3; ++i) {
for(int j = i + 1; j < nums.size() - 2; ++j) {
int start = j + 1;
int end = nums.size() - 1;
while(start < end) {
int sum = nums[i] + nums[j] + nums[start] + nums[end];
if(sum == target) {
vector<int> tmp;
tmp.push_back(nums[i]);
tmp.push_back(nums[j]);
tmp.push_back(nums[start]);
tmp.push_back(nums[end]);
res.push_back(tmp);
start++;
--end;
} else if(sum < target) start++;
else end--;
}
}
}
sort(res.begin(), res.end());
res.resize(unique(res.begin(), res.end()) - res.begin());
return res;
}
int main(void) {
vector<int> nums{1, 1, 1, 1, 1};
vector< vector<int> > res = FourSum(nums, 4);
for(int i = 0; i < res.size(); ++i) {
for(int j = 0; j < res[i].size(); ++j) {
cout << res[i][j] << " ";
}
cout << endl;
}
}
LeetCode 18. 4Sum
最新推荐文章于 2022-11-03 21:34:20 发布