leetcode877

leetcode877 Stone Game

思路:贪心策略显然不对 因此需要列举所有情况 使用dp降低时间复杂度(此题有数学解 可以证明Alex一定赢)

alex和lee是在头和尾轮流拿石头 dp记录时需要记录两端 因此是一个二维数组dp[ left][right];

以[5,3,4,5]为例 如果拿左边 剩下的是[3,4,5] ,dp[left][right] =piles[left]+dp[left+1][right] ? 因为Lee还要拿 所以 这个是不对的 剩下的[3,4,5]lee要拿掉头尾中的一个,实际上alex只能在[3,4]或者[4,5]中选取 因此dp[left][right] =piles[left]+max(dp[left+1][right-1],dp[left+2,right])
如果拿右边的 dp[left][right]=piles[right]+max(dp[left+1][right-1],dp[left,right-2]);
在左右中选一个最大的:
dp[left][right]=max(piles[left]+max(dp[left+1][right-1]dp[left+2,right]),piles[right]+max(dp[left+1][right-1],dp[left,right-2]);

class Solution {
public:
    using VV=vector<vector<int> >;
    using V=vector<int>;
    bool stoneGame(vector<int>& piles) {
        int n=piles.size();
        vector<vector<int> > dp(n,vector<int>(n,-1));
        vector<int> alex(n,0);// 标记alex选取的pile 可以不要 用piles总和减去alexsum
        int alexsum=maxsum(dp,alex,piles,0,n-1);
        int leesum=0;// 可以不用这么写 直接piles总和减去alexsum即可
        for(int i=0;i<n;++i){
            if(!alex[i]){
                leesum+=piles[i];
            }
        }
        //cout<<alexsum<<' '<<leesum<<endl;
        if(alexsum>leesum){
            return true;
        }else{
            return false;
        }
    }
    int maxsum(VV& dp,V& alex,V& piles,int left,int right){
        if(left>right)
            return 0;
        if(dp[left][right]!=-1)
            return dp[left][right];
        int choosel=piles[left]+max(maxsum(dp,alex,piles,left+1,right-1),maxsum(dp,alex,piles,left+2,right));
        int chooser=piles[right]+max(maxsum(dp,alex,piles,left+1,right-1),maxsum(dp,alex,piles,left,right-2));
        if(choosel>chooser){
            alex[left]=1;
            dp[left][right]=choosel;
        }else{
            dp[left][right]=chooser;
            alex[right]=1;
        }
        //cout<<"dp["<<left<<"]"<<"["<<right<<"]="<<dp[left][right];
        return dp[left][right];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值