Leetcode 3320. Count The Number of Winning Sequences

1. 解题思路

这一题的话就是一个比较常规的动态规划的题目,记录下当前轮次的score以及不允许出的召唤兽,然后考察在当前情况下后续要赢一共有多少种情况即可。

2. 代码实现

给出python代码实现如下:

MOD = 10**9+7

pn = [1 for _ in range(1001)]
for i in range(1, 1001):
    pn[i] = (2 * pn[i-1]) % MOD

class Solution:
    def countWinningSequences(self, s: str) -> int:
        n = len(s)
        
        def beats(c1, c2):
            if c1 == "F" and c2 == "E":
                return True
            elif c1 == "E" and c2 == "W":
                return True
            elif c1 == "W" and c2 == "F":
                return True
            return False
        
        @lru_cache(None)
        def dp(idx, forbid, points):
            if idx >= n:
                return 1 if points > 0 else 0
            if points > (n-idx):
                return pn[n-idx]
            elif points <= -(n-idx):
                return 0
            ans = 0
            for creature in "FWE":
                if creature == forbid:
                    continue
                if creature == s[idx]:
                    ans += dp(idx+1, creature, points)
                elif beats(creature, s[idx]):
                    ans += dp(idx+1, creature, points+1)
                else:
                    ans += dp(idx+1, creature, points-1)
            return ans % MOD
        
        return dp(0, "", 0)

提交代码评测得到:耗时4936ms,占用内存284.6MB。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值