-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombinationSumIV.cpp
More file actions
60 lines (54 loc) · 1.23 KB
/
Copy pathcombinationSumIV.cpp
File metadata and controls
60 lines (54 loc) · 1.23 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <bits/stdc++.h>
using namespace std;
// Combination Sum IV
class Solution
{
vector<long long> dp;
const int max = 2147483647;
public:
int combinationSum4(vector<int> &nums, int target)
{
dp.resize(target + 1, 0);
for (int i = 1; i <= target; i++)
{
for (int j = 0; j < nums.size(); j++)
{
if (nums[j] == i)
dp[i] += 1;
if (nums[j] < i)
dp[i] += dp[i - nums[j]];
dp[i] %= max;
}
}
for (int i = 0; i <= target; i++)
if (dp[i])
cout << i << " " << dp[i] << "\n";
return dp[target];
}
};
class Solution
{
public:
int combinationSum4(vector<int> &nums, int target)
{
vector<unsigned int> dp(target + 1);
dp[0] = 1;
for (int i = 1; i <= target; i++)
{
for (int n : nums)
if (i >= n)
dp[i] += dp[i - n];
}
return dp[target];
}
};
int main()
{
int n, target;
cin >> n;
vector<int> nums(n);
for (int &i : nums)
cin >> i;
cin >> target;
cout << Solution().combinationSum4(nums, target);
}