Skip to content

Commit 8da917d

Browse files
Create 0377-combination-sum-iv.java
1 parent 5fb0c45 commit 8da917d

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

java/0377-combination-sum-iv.java

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class Solution {
2+
3+
/* Tabulation Method
4+
--------------------------
5+
T = Target, N = nums.length
6+
Time complexity: O(T⋅N)
7+
Space complexity: O(T)
8+
*/
9+
10+
public int combinationSum4(int[] nums, int target) {
11+
int[] dp = new int[target+1];
12+
dp[0] = 1;
13+
14+
for(int currSum = 1; currSum < dp.length; currSum++){
15+
for(int no : nums){
16+
if(currSum - no >= 0){
17+
dp[currSum] += dp[currSum - no];
18+
}
19+
}
20+
}
21+
return dp[target];
22+
}
23+
24+
/* Memoization Method
25+
--------------------------
26+
T = Target, N = nums.length
27+
Time complexity: O(T⋅N)
28+
Space complexity: O(T) + Recursive Stack
29+
*/
30+
31+
public int combinationSum4(int[] nums, int target) {
32+
HashMap<Integer, Integer> memo = new HashMap<>();
33+
return helper(nums, target, memo);
34+
}
35+
36+
private int helper(int[] nums, int t, HashMap<Integer, Integer> memo){
37+
if(t == 0)
38+
return 1;
39+
if(t < 0)
40+
return 0;
41+
if(memo.containsKey(t))
42+
return memo.get(t);
43+
44+
int count = 0;
45+
for(int no : nums){
46+
count += helper(nums, t - no);
47+
}
48+
memo.put(t, count);
49+
return count;
50+
}
51+
}

0 commit comments

Comments
 (0)