-
Notifications
You must be signed in to change notification settings - Fork 14
/
4_sum.cpp
106 lines (90 loc) · 2.78 KB
/
4_sum.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
105
106
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<vector<int> > threeSum(vector<int> num, int target);
/*
* 1) Sort the array,
* 2) traverse the array, and solve the problem by using "3Sum" soultion.
*/
vector<vector<int> > fourSum(vector<int> &num, int target) {
vector< vector<int> > result;
if (num.size() < 4) return result;
sort( num.begin(), num.end() );
for(int i = 0; i < num.size() - 3; i++) {
//skip the duplication
if (i > 0 && num[i - 1] == num[i]) continue;
vector<int> n(num.begin()+i+1, num.end());
vector<vector<int> > ret = threeSum(n, target-num[i]);
for(int j = 0; j < ret.size(); j++) {
ret[j].insert(ret[j].begin(), num[i]);
result.push_back(ret[j]);
}
}
return result;
}
vector<vector<int> > threeSum(vector<int> num, int target) {
vector< vector<int> > result;
//sort the array (if the qrray is sorted already, it won't waste any time)
sort(num.begin(), num.end());
int n = num.size();
for (int i = 0; i < n - 2; i++) {
//skip the duplication
if (i > 0 && num[i - 1] == num[i]) continue;
int a = num[i];
int low = i + 1;
int high = n - 1;
while (low < high) {
int b = num[low];
int c = num[high];
if (a + b + c == target) {
//got the soultion
vector<int> v;
v.push_back(a);
v.push_back(b);
v.push_back(c);
result.push_back(v);
// Continue search for all triplet combinations