Skip to content

Commit d4d8e65

Browse files
authored
Create 0494-target-sum.kt
1 parent c385d4d commit d4d8e65

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

kotlin/0494-target-sum.kt

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
fun findTargetSumWays(nums: IntArray, target: Int): Int {
3+
val memo = HashMap<String, Int>()
4+
5+
fun dfs(i: Int, sum: Int): Int {
6+
if (i == nums.size)
7+
return if (sum == target) 1 else 0
8+
val key = "$i:$sum"
9+
if (key in memo)
10+
return memo[key]!!
11+
memo[key] = dfs(i + 1, sum + nums[i]) +
12+
dfs(i + 1, sum - nums[i])
13+
return memo[key]!!
14+
}
15+
16+
return dfs(0, 0)
17+
}
18+
}

0 commit comments

Comments
 (0)