[Leetcode][Python] Stone Game I,IV总结

本文解析了LeetCode上的石头游戏系列问题,包括Stone Game I和Stone Game IV。通过动态规划的方法解决了玩家如何在游戏中获得优势的问题,并提供了详细的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[Leetcode][Python] Stone Game I,II,III,IV总结

Stone Game I

题目链接:https://leetcode.com/problems/stone-game/

题目解析:DP问题
dp[i][j]: 从第i个石头到第 j 即 (i+l-1)个石头之间最大的对手得分差。
Alex取piles[i]时,Lee也保持最佳状态从[ i+1, j ]中取值
Alex取piles[j]时,Lee也保持最佳状态从[ i, j+1 ]中取值

代码

def stoneGame(piles) -> bool:
    n = len(piles)
    dp = [[0 for i in range(n)] for j in range(n)]
    for i in range(n):
        dp[i][i] = piles[i]
        for l in range(2,n+1): # subproblem with length [2,n]
            for i in range(n-l+1):
                j = i + l -1
                dp[i][j]=max(piles[i]-dp[i+1][j],piles[j]-dp[i][j-1])
    return dp[0][n-1] > 0

Stone Game IV

题目链接:https://leetcode.com/problems/stone-game-iv/
题目解析:DP问题
举例:
i=1,Alice拿1,获胜。
i=2,Alice拿1,dp[2-1] 先拿者获胜,Bob获胜,Alice输。
i=3,Alice拿1,dp[3-1] 先拿者输,Bob输,Alice获胜。
i=4,Alice拿4,Alice获胜。
i=5,Alice拿4,dp[5-1]或者dp[5-4]先拿者胜,Alice输。
以此类推…

代码

class Solution(object):
    def winnerSquareGame(self, n):
        """
        :type n: int
        :rtype: bool
        """
        dp = [False] * (n + 1)
        for i in range(1, n + 1):
            for j in range(1, int(i ** 0.5 + 1)):
                if not dp[i - j * j]:
                    dp[i] = 1
                    break
        return dp[n]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值