-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCombinationSumIV.java
71 lines (61 loc) · 1.78 KB
/
CombinationSumIV.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
59
60
61
62
63
64
65
66
67
68
69
70
71
//Approach 1: 100% Faster Dynamic Programming - Top Down Approach
// Time Complexity: O(n*target) | Space Complexity: O(target)
/*
Runtime: 0 ms, faster than 100.00% of Java online submissions for Combination Sum IV.
Memory Usage: 39.9 MB, less than 87.07% of Java online submissions for Combination Sum IV.
*/
class Solution {
static int[] dp;
public int combinationSum4(int[] nums, int target) {
dp = new int[target + 1];
Arrays.fill(dp, -1);
dp[0] = 1;
helper(nums, target);
return dp[target];
}
public static int helper(int[] nums, int target){
if(dp[target]> -1){
return dp[target];
}
int res = 0;
for(int i : nums){
if(i<=target){
res += helper(nums, target-i);
}
}
dp[target] = res;
return dp[target];
}
}
//Approach 2: 92% Faster Dynamic Programming - Bottom Up Approach
// Time Complexity: O(n*target) | Space Complexity: O(target)
class Solution {
static int[] dp;
public int combinationSum4(int[] nums, int target) {
dp = new int[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];
}
}
//Approach 3:(Recursion) Brute Force --> Works, but TLE in Online Compilers
class Solution {
public int combinationSum4(int[] nums, int target) {
if(target == 0){
return 1;
}
int res = 0;
for(int i : nums){
if(i<=target){
res += combinationSum4(nums, target-i);
}
}
return res;
}
}