-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpermutation_sum.cpp
62 lines (53 loc) · 1.32 KB
/
permutation_sum.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
/*
problem link: https://leetcode.com/problems/combination-sum-iv/
this is basically subset sum == k
but 1,1,2 is different than 1,2,1
so we need to count both
hence for each subproblem, instead of just visiting idx-1, we need to visit entire array
*/
#include <iostream>
#include <vector>
using namespace std;
class RecSolution
{
public:
int f(int target, vector<int> &nums)
{
if (target < 0)
return 0;
if (target == 0)
return 1;
int ways = 0;
for (int num : nums)
ways += f(target - num, nums);
return ways;
}
int combinationSum4(vector<int> &nums, int target)
{
// for every sub-problem, consider entire array
return f(target, nums);
}
};
class MemoSolution
{
public:
int f(int target, vector<int> &nums, vector<int> &dp)
{
if (target < 0)
return 0;
if (target == 0)
return 1;
if (dp[target] != -1)
return dp[target];
int ways = 0;
for (int num : nums)
ways += f(target - num, nums, dp);
return dp[target] = ways;
}
int combinationSum4(vector<int> &nums, int target)
{
// for every sub-problem, consider entire array
vector<int> dp(target + 1, -1);
return f(target, nums, dp);
}
};