Last active
June 22, 2021 19:02
-
-
Save m00nlight/598f531790b02e1a0ed6f610f2372d6e to your computer and use it in GitHub Desktop.
Leetcode Target sum DP solution in Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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