Skip to content

Commit

Permalink
Create 0494-target-sum.kt
Browse files Browse the repository at this point in the history
  • Loading branch information
a93a authored May 4, 2023
1 parent c385d4d commit d4d8e65
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions kotlin/0494-target-sum.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
class Solution {
fun findTargetSumWays(nums: IntArray, target: Int): Int {
val memo = HashMap<String, Int>()

fun dfs(i: Int, sum: Int): Int {
if (i == nums.size)
return if (sum == target) 1 else 0
val key = "$i:$sum"
if (key in memo)
return memo[key]!!
memo[key] = dfs(i + 1, sum + nums[i]) +
dfs(i + 1, sum - nums[i])
return memo[key]!!
}

return dfs(0, 0)
}
}

0 comments on commit d4d8e65

Please sign in to comment.