-
Notifications
You must be signed in to change notification settings - Fork 242
/
Copy pathCombinationSum4.cpp
72 lines (53 loc) · 1.57 KB
/
CombinationSum4.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
// https://leetcode.com/problems/combination-sum-iv/description/
class Solution {
public:
// Simple Recursive Solution
// int solve(vector<int> &nums, int target){
// if(target==0){
// return 1;
// }
// else if(target<0)
// return 0;
// int ans= 0;
// for(auto i : nums){
// ans += solve(nums, target-i, dp);
// }
// return ans;
// }
// Recursion + Memoization (Top-Down Approach)
// int solve(vector<int> &nums, int target, vector<int> &dp){
// if(target==0){
// return 1;
// }
// else if(target<0)
// return 0;
// if(dp[target]!=-1)
// return dp[target];
// int ans= 0;
// for(auto i : nums){
// ans += solve(nums, target-i, dp);
// }
// dp[target]= ans;
// return dp[target];
// }
int solve(vector<int> &nums, int target){
vector<int> dp(target+1, 0);
dp[0]= 1;
for(int i=0; i<=target; i++){
for(auto j : nums){
if(i-j>=0){
dp[i] += dp[i-j]*1l;
}
}
}
return dp[target];
}
int combinationSum4(vector<int>& nums, int target) {
// Simple Recursive Solution
// return solve(nums, target);
// Recursion + Memoization (Top-Down Approach)
// vector<int> dp(target+1, -1);
// return solve(nums, target, dp);
return solve(nums, target);
}
};