LeetCode 486 Predict the Winner 题解
来源:互联网 发布:苹果桌面主题软件 编辑:程序博客网 时间:2024/06/05 05:03
题目简述:给定非负数组nums。有两个玩家,从玩家1开始交替取出一个数并加到他的分数上,取的时候只能取数组剩余的头尾两个数之一。当所有数都被取完时分数高的玩家获胜。求在给定nums的情况下,预测玩家1是否获胜。假设两个玩家每次都会做出最优选择。
输入:非负数组nums。
输出:一个bool值,表示玩家1是否获胜。
示例:对于数组[1,5,2],玩家1必输,因为无论取1还是2,玩家2都会取5而获胜。
题解:
这是一个最大最小策略的博弈问题。考虑使用动态规则求在某个状态下所能获得的分数最大值。记
状态转移方程是:
简单解释一下,对于区间[i,j],都是两种取法,那么就取这两个方法中更高分数的那个。一旦取了一个数,由于对手也会做最优选择,因此你在剩余的区间得到的分数肯定是最小的。
然后根据
初始状态是
这个状态转移方程显然可以用递推实现,先从区间长度为1的
最后进行空间上的优化,注意到求出
算法实现如下,时间复杂度是O(
class Solution {public: bool PredictTheWinner(vector<int>& nums) { int dp[21], sum[21]; sum[0] = 0; for(int i = 0;i < nums.size();i++) { sum[i+1] = sum[i] + nums[i]; dp[i] = nums[i]; } for(int i = 1;i < nums.size();i++) { for(int j = 0;j < nums.size() - i;j++) { dp[j] = sum[j+i+1] - sum[j] - min(dp[j], dp[j+1]); } } if(2*dp[0] >= sum[nums.size()]) return true; else return false; }};
0 0
- LeetCode 486 Predict the Winner 题解
- [leetcode] predict the winner
- [LeetCode] Predict the Winner
- Predict the Winner(leetcode)
- LeetCode486. Predict the Winner题解
- LeetCode题解(Week 9):486. Predict the Winner
- 【486】 Predict the Winner
- [LeetCode]486. Predict the Winner
- LeetCode 486. Predict the Winner
- [leetcode]486. Predict the Winner
- LeetCode 486. Predict the Winner
- LeetCode 486. Predict the Winner
- leetcode:486. Predict the Winner
- 【Leetcode】486. Predict the Winner
- Leetcode 486. Predict the Winner
- LeetCode 486. Predict the Winner
- LeetCode 486. Predict the Winner
- leetcode 486. Predict the Winner
- Effective前端2:优化html标签
- 全排列
- 贪心 -- 活动选择
- Effective前端1:能使用html/css解决的问题就不要使用JS
- redis学习笔记
- LeetCode 486 Predict the Winner 题解
- GDOI2017模拟 第三场(4.19~4.21)
- 怎样写一个webpack loader
- Linux中千M网卡与自适应的关系
- 分布式消息队列RocketMQ源码分析之3 -- Consumer负载均衡机制 -- Rebalance
- 从数据挖掘经典算法PageRank入门
- Webpack从入门到上线
- Linux C文件操作(三)
- 字符数组的定义和初始化