-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathMultisetSum.java
58 lines (52 loc) · 1.37 KB
/
MultisetSum.java
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
/*https://binarysearch.com/problems/Multiset-Sum*/
import java.util.*;
class Solution {
public int solve(int[] nums, int k) {
return recur(nums, k, 0);
}
public int recur(int[] nums, int k, int index)
{
if (k == 0) return 1;
int i, result = 0;
for (i = index; i < nums.length; ++i)
if (nums[i] <= k)
result += recur(nums, k-nums[i], i);
return result;
}
}
import java.util.*;
class Solution {
Integer[][] memo;
public int solve(int[] nums, int k) {
memo = new Integer[nums.length+1][k+1];
memo[0][k] = recur(nums, k, 0);
return memo[0][k];
}
public int recur(int[] nums, int k, int index)
{
if (k == 0)
{
memo[index][k] = 1;
return 1;
}
if (memo[index][k] != null) return memo[index][k];
int i, result = 0;
for (i = index; i < nums.length; ++i)
if (nums[i] <= k)
result += recur(nums, k-nums[i], i);
memo[index][k] = result;
return result;
}
}
import java.util.*;
class Solution {
public int solve(int[] nums, int k) {
int[] memo = new int[k+1];
memo[0] = 1;
int sum;
for (int num : nums)
for (sum = num; sum <= k; ++sum)
memo[sum] += memo[sum-num];
return memo[k];
}
}