Leetcode 2466. Count Ways To Build Good Strings

Problem

Given the integers zero, one, low, and high, we can construct a string by starting with an empty string, and then at each step perform either of the following:

  • Append the character ‘0’ zero times.
  • Append the character ‘1’ one times.

This can be performed any number of times.

A good string is a string constructed by the above process having a length between low and high (inclusive).

Return the number of different good strings that can be constructed satisfying these properties. Since the answer can be large, return it modulo 1 0 9 + 7 10^9 + 7 109+7.

Algorithm

Dynamic Programming (DP). Define dp[i] as the number of valid strings of length i that can be formed using the given rules.
d p [ i ] = d p [ i − zero ] + d p [ i − one ] dp[i] = dp[i - \text{zero}] + dp[i - \text{one}] dp[i]=dp[izero]+dp[ione]

This is valid if i - zero >= 0 and i - one >= 0.

Code

class Solution:
    def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int:
        dp = [0] * (high + 1)
        dp[0] = 1
        for i in range(high + 1):
            if i >= zero:
                dp[i] = (dp[i] + dp[i - zero]) % 1000000007
            if i >= one:
                dp[i] = (dp[i] + dp[i - one]) % 1000000007
        
        ans = 0
        for i in range(low, high+1):
            ans = (ans + dp[i]) % 1000000007
        return ans
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值