数位dp-记忆化写法和DP写法

题目

记忆化写法

@lru_cache(None)
def dfs(i: int, s: int, is_limit: bool, is_num: bool) -> int:
    if i == len(k):
        return int(s > 0 and s % D == 0)
    ret = 0

    if not is_num:
        ret += dfs(i + 1, s, False, False)

    low = 0 if is_num else 1
    up = int(k[i]) if is_limit else 9
    for x in range(low, up + 1):
        ret += dfs(i + 1, s + x, is_limit and x == int(k[i]), True)
        ret %= mod
    return ret


rst = dfs(0, 0, True, False)

DP写法 参考别人的代码

class mint(int):
    MOD = 10 ** 9 + 7

    def __add__(self, other):
        return mint(int.__add__(self, other) % self.MOD)

    def __sub__(self, other):
        return mint(int.__sub__(self, other) % self.MOD)

    def __mul__(self, other):
        return mint(int.__mul__(self, other) % self.MOD)

    def __truediv__(self, other):
        return mint(int.__mul__(self, pow(other, -1, self.MOD)) % self.MOD)
   
dp = [[[mint(0)] * 2 for i in range(D)] for j in range(N + 1)]
dp[0][0][0] = mint(1)
for i in range(N):
    for d in range(D):
        a = K[N - 1 - i]
        for j in range(10):
            if j <= a:
                dp[i + 1][(d + j) % D][0] += dp[i][d][0]
            else:
                dp[i + 1][(d + j) % D][1] += dp[i][d][0]

            if j < a:
                dp[i + 1][(d + j) % D][0] += dp[i][d][1]
            else:
                dp[i + 1][(d + j) % D][1] += dp[i][d][1]
print(dp[N][0][0] - 1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值