Skip to content

Instantly share code, notes, and snippets.

@m00nlight
Last active June 22, 2021 19:02
Show Gist options
  • Save m00nlight/598f531790b02e1a0ed6f610f2372d6e to your computer and use it in GitHub Desktop.
Save m00nlight/598f531790b02e1a0ed6f610f2372d6e to your computer and use it in GitHub Desktop.
Leetcode Target sum DP solution in Kotlin
import kotlin.math.abs
// https://leetcode.com/problems/target-sum/
// dp function: dp[i][j] = dp[i - 1][j - nums[i]] + dp[i - 1][j + nums[i]]
class TargetSum {
fun findTargetSumWays(nums: IntArray, target: Int): Int {
val dp = Array(nums.size + 1) { mutableMapOf<Int, Int>().withDefault { 0 } }
dp[0][0] = 1
for (i in 1..nums.size) {
for (t in -abs(nums.sum())..abs(nums.sum())) {
dp[i][t] = dp[i - 1].getValue(t - nums[i - 1]) + dp[i - 1].getValue(t + nums[i - 1])
}
}
return dp[nums.size].getOrDefault(target, 0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment