forked from fengvyi/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
018. 4Sum.cpp
25 lines (24 loc) · 904 Bytes
/
018. 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
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
vector<vector<int>>res;
vector<int>path;
DFS(res, nums, 0, target, 0, 0, path);
return res;
}
void DFS(vector<vector<int>>& res, vector<int>& nums, int pos, int target, int count, int sum, vector<int>& path){
if(count == 4){
if(sum == target) res.push_back(path);
return;
}
for(int i = pos; i < nums.size(); i++){
if(i != pos && nums[i] == nums[i - 1]) continue;
if(sum + nums[i] + (3 - count) * nums[nums.size() - 1] < target) continue;
if(sum + (4 - count)* nums[i] > target) break;
path.push_back(nums[i]);
DFS(res, nums, i + 1, target, count + 1, sum + nums[i], path);
path.pop_back();
}
}
};