forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0377-combination-sum-iv.kt
More file actions
38 lines (31 loc) · 847 Bytes
/
0377-combination-sum-iv.kt
File metadata and controls
38 lines (31 loc) · 847 Bytes
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
//dp solution
class Solution {
fun combinationSum4(nums: IntArray, target: Int): Int {
val dp = IntArray(target + 1)
dp[0] = 1
for (i in 1..target) {
for (n in nums) {
if(i - n >= 0) dp[i] += dp[i - n]
}
}
return dp[target]
}
}
//recursion + memoization solution
class Solution {
fun combinationSum4(nums: IntArray, target: Int): Int {
val dp = HashMap<Int, Int>()
fun dfs(sum: Int): Int {
if (sum == target) return 1
if (sum in dp) return dp[sum]!!
var res = 0
for (num in nums) {
if (sum + num <= target)
res += dfs(sum + num)
}
dp[sum] = res
return res
}
return dfs(0)
}
}