forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
55 lines (39 loc) · 1.05 KB
/
main.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
/// Source : https://leetcode.com/problems/combination-sum-iv/description/
/// Author : liuyubobobo
/// Time : 2018-03-04
#include <iostream>
#include <vector>
using namespace std;
/// Memory Search
/// Time Complexity: O(n * target)
/// Space Complexity: O(n * target)
class Solution {
private:
vector<int> memo;
public:
int combinationSum4(vector<int>& nums, int target) {
if(nums.size() == 0)
return 0;
memo = vector<int>(target + 1, -1);
solve(nums, target);
return memo[target];
}
private:
int solve(const vector<int>& nums, int target){
if(target == 0)
return 1;
if(memo[target] != -1)
return memo[target];
int res = 0;
for(int i = 0; i < nums.size() ; i ++)
if(target >= nums[i])
res += solve(nums, target - nums[i]);
return memo[target] = res;
}
};
int main() {
vector<int> nums1 = {1, 2, 3};
int target1 = 4;
cout << Solution().combinationSum4(nums1, target1) << endl;
return 0;
}