-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0040-combination-sum-ii.cpp
More file actions
42 lines (38 loc) · 1.27 KB
/
Copy path0040-combination-sum-ii.cpp
File metadata and controls
42 lines (38 loc) · 1.27 KB
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
class Solution {
public:
vector<vector<int>> ans;
map<int, int> counts;
void solve(vector<pair<int,int>>& nums, int sum, int index, vector<int>& cur) {
if (sum == 0) {
ans.push_back(cur);
return;
}
if (index >= nums.size()) return;
solve(nums, sum, index + 1, cur);
pair<int,int> p = nums[index];
int old_size = cur.size();
for (int i = 0; i < p.second && sum >= p.first; ++i) {
cur.push_back(p.first);
sum -= p.first;
solve(nums, sum, index + 1, cur);
}
while(cur.size() > old_size) cur.pop_back();
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
counts.clear();
for (int i = 0; i < candidates.size(); ++i) {
int p = candidates[i];
if (counts.find(p) == counts.end()) counts[p] = 1;
else counts[p]++;
}
vector<pair<int,int>> nums;
for (map<int,int>::iterator it = counts.begin();
it != counts.end(); ++it) {
nums.push_back(make_pair(it->first, it->second));
}
ans.clear();
vector<int> cur;
solve(nums, target, 0, cur);
return ans;
}
};