博客
关于我
LeetCode 486. 预测赢家(dp)
阅读量:226 次
发布时间:2019-03-01

本文共 903 字,大约阅读时间需要 3 分钟。

题意

给定一个表示分数的非负整数数组,玩家1和玩家2将按照规则轮流从数组两端拿取分数。玩家1先手,随后玩家2从剩余的另一端拿取,依此类推,直到分数全部拿完。最终,总分数较高的玩家获胜。如果两人的总分数相等,玩家1仍为赢家。

解法

这个问题可以通过动态规划来解决。我们定义d[i][j]为从数组的第i个元素到第j个元素这段区间中,当前先手玩家能够获得的最大分数。递归关系式如下:

d[i][j] = max(a[i] - d[i+1][j], a[j] - d[i][j-1])

其中,a[i]表示当前玩家从左端拿取的分数,而a[j]表示从右端拿取的分数。玩家会选择使自己总分数最大的选项,即max(a[i] - d[i+1][j], a[j] - d[i][j-1])。

代码

class Solution {private:    int d[22][22];    int a[22];    int dp(int l, int r) {        if (l == r) {            return a[l];        }        if (d[l][r] != -1) {            return d[l][r];        }        return d[l][r] = std::max(a[l] - dp(l + 1, r), a[r] - dp(l, r - 1));    }    bool PredictTheWinner(std::vector
aa) { int n = aa.size(); for (int i = 0; i < n; ++i) { a[i+1] = aa[i]; } dp(1, n); return d[1][n] >= 0; }};

这个代码定义了一个动态规划数组d[l][r],用于存储从位置l到r的最大分数差值。通过递归调用,计算出每个子区间的最优策略,最终判断玩家1是否能成为赢家。

转载地址:http://mwuv.baihongyu.com/

你可能感兴趣的文章
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>
no1
查看>>
NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
查看>>
NOAA(美国海洋和大气管理局)气象数据获取与POI点数据获取
查看>>