Skip to content

Commit b56cbc8

Browse files
authored
Update 0377-combination-sum-iv.kt
1 parent aaf69d7 commit b56cbc8

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

kotlin/0377-combination-sum-iv.kt

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
//dp solution
12
class Solution {
23
fun combinationSum4(nums: IntArray, target: Int): Int {
34
val dp = IntArray(target + 1)
@@ -12,3 +13,26 @@ class Solution {
1213
return dp[target]
1314
}
1415
}
16+
17+
//recursion + memoization solution
18+
class Solution {
19+
fun combinationSum4(nums: IntArray, target: Int): Int {
20+
val dp = HashMap<Int, Int>()
21+
22+
fun dfs(sum: Int): Int {
23+
if (sum == target) return 1
24+
if (sum in dp) return dp[sum]!!
25+
26+
var res = 0
27+
for (num in nums) {
28+
if (sum + num <= target)
29+
res += dfs(sum + num)
30+
}
31+
32+
dp[sum] = res
33+
return res
34+
}
35+
36+
return dfs(0)
37+
}
38+
}

0 commit comments

Comments
 (0)