Skip to content

Commit

Permalink
Create 2466-count-ways-to-build-good-strings.kt
Browse files Browse the repository at this point in the history
  • Loading branch information
a93a authored May 13, 2023
1 parent fd22564 commit 1939100
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions kotlin/2466-count-ways-to-build-good-strings.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
* Recursion/DFS + memoization
*/
class Solution {
fun countGoodStrings(low: Int, high: Int, zero: Int, one: Int): Int {
val dp = IntArray(high + 1) { -1 }
val mod = 1000000007

fun dfs(i: Int): Int {
if (i > high)
return 0
if (dp[i] != -1)
return dp[i]

dp[i] = if (i >= low) 1 else 0
dp[i] += dfs(i + zero) + dfs(i + one)
dp[i] = dp[i] % mod

return dp[i]
}

return dfs(0)
}
}

/*
* Bottom up DP
*/
class Solution {
fun countGoodStrings(low: Int, high: Int, zero: Int, one: Int): Int {
val dp = IntArray(high + 1)
val mod = 1000000007

dp[0] = 1
for (i in 1..high) {
dp[i] += if (i - one >= 0) dp[i - one] else 0
dp[i] += if (i - zero >= 0) dp[i - zero] else 0
dp[i] = dp[i] % mod
}

var sum = 0
for (i in low..high) sum = (sum + dp[i]) % mod
return sum
}
}

0 comments on commit 1939100

Please sign in to comment.