-
Notifications
You must be signed in to change notification settings - Fork 2
/
18.cpp
107 lines (94 loc) · 2.79 KB
/
18.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// Author : Accagain
// Date : 17/2/16
// Email : chenmaosen0@gmail.com
/***************************************************************************************
*
* 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: 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]
* ]
*
* 做法:
*
* 时间复杂度:
* O(n^3)
*
****************************************************************************************/
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
#define INF 0x3fffffff
using namespace std;
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> ans;
sort(nums.begin(), nums.end());
for(int i=0; i<nums.size(); i++)
{
if((i > 0) && (nums[i] == nums[i-1]))
continue;
int now = nums[i];
for(int j=i+1; j<nums.size(); j++)
{
int next = nums[j];
if((j-i>=2) && (nums[j] == nums[j-1]))
continue;
int l = j+1;
int r = nums.size() - 1;
while(l < r)
{
int sum = now + next + nums[l] + nums[r];
if(sum > target)
r--;
else if( sum < target)
l++;
else
{
int tmp[] = {now, next, nums[l], nums[r]};
vector<int> x(tmp, tmp+sizeof(tmp)/sizeof(tmp[0]));
ans.push_back(x);
while((l+1 < r) && (nums[l] == nums[l+1]))
{
l++;
continue;
}
while((l < r-1) && (nums[r] == nums[r-1]))
{
r--;
continue;
}
l++;
r--;
}
}
}
}
return ans;
}
};
int main() {
Solution *test = new Solution();
int data[] = {1,-2,-5,-4,-3,3,3,5};
vector<int> x(data, data + sizeof(data) / sizeof(data[0]));
vector<vector<int>> ans = test->fourSum(x, -11);
for(int i=0; i<ans.size(); i++)
{
for(int j=0; j<ans[i].size(); j++)
printf("%d ", ans[i][j]);
putchar('\n');
}
return 0;
}