-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCombinationSum4.java
53 lines (44 loc) · 1.17 KB
/
CombinationSum4.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
package org.sean.dynamicpro;
/***
* 377. Combination Sum IV
*/
public class CombinationSum4 {
// region DP : O(N*M)
public int combinationSum4(int[] nums, int target) {
// dp[i] : number of combinations for target i
int[] dp = new int[target + 1];
dp[0] = 0;
for (int e : nums) {
if (e <= target) {
dp[e] = 1;
}
}
int len = nums.length;
for (int k = 1; k <= target; k++) {
for (int i = 0; i < len; i++) {
if (k > nums[i])
dp[k] += dp[k - nums[i]];
}
}
return dp[target];
}
// endregion
// region DFS : TLE O(N^M)
private int count;
private void combinationSum4Helper(int[] nums, int target) {
if (target == 0) {
count++;
return ;
}
if (target < 0)
return;
for (int i = 0; i < nums.length; i++) {
combinationSum4Helper(nums, target- nums[i]);
}
}
public int combinationSum40(int[] nums, int target) {
combinationSum4Helper(nums, target);
return count;
}
// endregion
}