-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0039.cpp
60 lines (52 loc) · 1.43 KB
/
0039.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
#include <vector>
using namespace std;
// Time: O(2^target), Space: O(target)
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> ans;
vector<int> cur;
helper(candidates, target, 0, cur, ans);
return ans;
}
void helper(vector<int>& cand, int target, int idx, vector<int> &cur, vector<vector<int>> &ans)
{
if (idx >= cand.size() || target < 0) return ;
else if (target == 0)
{
ans.push_back(cur);
return ;
}
// pick or not
cur.push_back(cand[idx]);
helper(cand, target-cand[idx], idx, cur, ans);
cur.pop_back();
helper(cand, target, idx+1, cur, ans);
}
};
// K knapsack
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<vector<int>>> dp(target+1);
for (int num : candidates)
{
for (int i = num; i <= target; i++)
{
if (i == num)
dp[i].push_back({num});
else
{
for (auto prev : dp[i-num])
{
prev.push_back(num);
dp[i].push_back(prev);
}
}
}
}
return dp[target];
}
};