Leetcode 3320. Count The Number of Winning Sequences
- Leetcode 3320. Count The Number of Winning Sequences
- 1. 解题思路
- 2. 代码实现
- 题目链接: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。