博客
关于我
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/

你可能感兴趣的文章
notepad++最详情汇总
查看>>
notepad++正则表达式替换字符串详解
查看>>
notepad如何自动对齐_notepad++怎么自动排版
查看>>
Notes on Paul Irish's "Things I learned from the jQuery source" casts
查看>>
Notification 使用详解(很全
查看>>
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
查看>>
NotImplementedError: Could not run torchvision::nms
查看>>
nova基于ubs机制扩展scheduler-filter
查看>>
Now trying to drop the old temporary tablespace, the session hangs.
查看>>
nowcoder—Beauty of Trees
查看>>
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
查看>>
np.power的使用
查看>>
NPM 2FA双重认证的设置方法
查看>>
npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
查看>>
npm build报错Cannot find module ‘webpack‘解决方法
查看>>
npm ERR! ERESOLVE could not resolve报错
查看>>
npm ERR! fatal: unable to connect to github.com:
查看>>
npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
查看>>
npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
查看>>
npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
查看>>