[leetcode]877. Stone Game

本文解析了LeetCode上StoneGame题目,并提供了一种动态规划解决方案。文章详细介绍了如何通过构建状态转移方程来求解该问题,即使在题目存在漏洞的情况下也能找到正确的解答路径。

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

[leetcode]877. Stone Game


Analysis

paper 被拒了,改了一个礼拜,心塞,然后回家过暑假了—— [我胡汉三又回来了!]

Alex and Lee play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].
The objective of the game is to end with the most stones. The total number of stones is odd, so there are no ties.
Alex and Lee take turns, with Alex starting first. Each turn, a player takes the entire pile of stones from either the beginning or the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins.
Assuming Alex and Lee play optimally, return True if and only if Alex wins the game.
虽然题目出的有bug,就是不管什么情况都是Alex赢,所以只要返回true就能AC,但是我们还是按照一般的动态规划问题解决。
我讨厌动态规划啊!参考了大神们的解法,这个博客解释的比较清楚:
https://blog.youkuaiyun.com/androidchanhao/article/details/81271077

Implement

class Solution {
public:
    bool stoneGame(vector<int>& piles) {
        int len = piles.size();
        vector<vector<int> > dp(len, vector<int>(len, 0));
        for(int i=0; i<len; i++)
            dp[i][i] = piles[i];
        for(int dis=1; dis<len; dis++){
            for(int i=0; i<len-dis; i++)
                dp[i][i+dis] = max(piles[i]-dp[i+1][i+dis], piles[i+dis]-dp[i][i+dis-1]);
        }
        return dp[0][len-1]>0;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值