LintCode-硬币排成线 III

本文探讨了一种博弈问题,即两名玩家轮流从一排硬币的两端取走一枚,最终获得金额较多者获胜。通过动态规划的方法,文章提供了一个解决方案来判断先手玩家是否能够赢得比赛。

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

There are n coins in a line. Two players take turns to take a coin from one of the ends of the line until there are no more coins left. The player with the larger amount of money wins.

Could you please decide the first player will win or lose?

样例

Given array A = [3,2,2], return true.

Given array A = [1,2,4], return true.

Given array A = [1,20,4], return false.

挑战

Follow Up Question:

If n is even. Is there any hacky algorithm that can decide whether first player will win or lose in O(1) memory and O(n) time?

分析:这个一看感觉就是动态规划,但是状态确实有点难表示,可以用dp[i][j]表示从i到j这一段,先手的最大值和后手的最大值,用一个pair<int,int>保存,如果已知dp[i+1][j]和dp[i][j-1],那么就可以枚举两端确定dp[i][j]

代码:

class Solution {
public:
    /**
     * @param values: a vector of integers
     * @return: a boolean which equals to true if the first player will win
     */
    bool firstWillWin(vector<int> &values) {
        // write your code here
        int n = values.size();
        vector<vector<pair<int,int> > > dp(n,vector<pair<int,int> >(n,make_pair(0,0)));
        for(int len=1;len<=n;len++)
        {
            for(int i=0;i+len<=n;i++)
            {
                int j = i+len-1;
                if(i==j)
                    dp[i][j] = make_pair(values[i],0);
                else
                {
                    pair<int,int> p1 = dp[i+1][j];
                    pair<int,int> p2 = dp[i][j-1];
                    if(p1.second+values[i]>p2.second+values[j])
                    {
                        dp[i][j] = make_pair(p1.second+values[i],p1.first);
                    }
                    else
                    {
                        dp[i][j] = make_pair(p2.second+values[j],p2.first);
                    }
                }
            }
        }
        if(dp[0][n-1].first>dp[0][n-1].second)
            return true;
        else
            return false;
    }
};


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值