-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCombinationSum-II_40.cpp
87 lines (62 loc) · 2.11 KB
/
CombinationSum-II_40.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
/*
~ Author : https://leetcode.com/tridib_2003/
~ Problem : 40. Combination Sum II
~ Link : https://leetcode.com/problems/combination-sum-ii/
*/
// Approach 1
class Solution {
public:
void combinationSum2Util(int idx, int target, vector<int>& nums, vector<int>& curr, vector<vector<int>>& ans) {
if (target == 0) {
ans.emplace_back(curr);
return;
}
for (int i = idx; i < nums.size(); ++i) {
if (i > idx && nums[i] == nums[i - 1])
continue;
if (nums[i] > target)
break;
curr.emplace_back(nums[i]);
combinationSum2Util(i + 1, target - nums[i], nums, curr, ans);
curr.pop_back();
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<vector<int>> ans;
vector<int> curr;
combinationSum2Util(0, target, candidates, curr, ans);
return ans;
}
};
// Approach 2 (Uses logn extra-time than approach 1 for storing elements in the set)
/*
class Solution {
public:
void combinationSum2Util(int idx, int target, vector<int>& nums, vector<int>& curr, set<vector<int> >& ans) {
if (target == 0) {
ans.insert(curr);
return;
}
if (idx == nums.size())
return;
if (nums[idx] <= target) {
curr.emplace_back(nums[idx]);
combinationSum2Util(idx + 1, target - nums[idx], nums, curr, ans);
curr.pop_back();
}
combinationSum2Util(idx + 1, target, nums, curr, ans);
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
set<vector<int> > ans;
vector<int> curr;
combinationSum2Util(0, target, candidates, curr, ans);
vector<vector<int> > res;
for (auto i : ans) {
res.emplace_back(i);
}
return res;
}
};
*/