-
-
Notifications
You must be signed in to change notification settings - Fork 110
/
4Sum.cpp
35 lines (26 loc) · 1.07 KB
/
4Sum.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
vector<vector<int>> fourSum(vector<int>& nums, int target) {
int n = nums.size();
sort(nums.begin() , nums.end()); // sort the array to use the two pointers method
vector<vector<int>> ans;
set<vector<int>> store; // to store and remove the duplicate answers
for(int i = 0 ; i < n; i++){
for(int j = i + 1; j < n ; j++){
int new_target = target - nums[i] - nums[j];
int x = j+1 , y = n-1;
while(x < y){
int sum = nums[x] + nums[y];
if(sum > new_target) y--;
else if(sum < new_target ) x++;
else {
store.insert({nums[i] , nums[j] , nums[x] , nums[y]});
x++;
y--;
};
}
}
}
for(auto i : store){
ans.push_back(i); // store the answers in an array(ans)
}
return ans;
}