[LeetCode]486. Predict the Winner
来源:互联网 发布:淘宝美国兔妈是真货吗 编辑:程序博客网 时间:2024/05/16 18:41
https://leetcode.com/problems/predict-the-winner/
给一个int数组,两个人依次从数组任意一头拿一个数,判断player1最后拿到的总数是否更大
两人依次拿,如果P1赢,则P1拿的>P2拿的。我们把P1拿的视为“+”,把P2拿的视为“-”,如果最后结果大于等于0则P1赢。
因此对于递归来说,beg ~ end的结果为max(nums[beg] - partition(beg + 1, end), nums[end] - partition(beg, end + 1));对于非递归来说DP[beg][end]表示即为beg ~ end所取的值的大小(最终与零比较)
本题两解:
递归:
public class Solution { public boolean PredictTheWinner(int[] nums) { int ret = partition(nums, 0, nums.length - 1, new Integer[nums.length][nums.length]); return ret >= 0; } private int partition(int[] nums, int beg, int end, Integer[][] cache) { if (cache[beg][end] == null) { cache[beg][end] = beg == end ? nums[beg] : Math.max(nums[beg] - partition(nums, beg + 1, end, cache), nums[end] - partition(nums, beg, end - 1, cache)); } return cache[beg][end]; }}
非递归:
public class Solution { public boolean PredictTheWinner(int[] nums) { if (nums == null || nums.length == 0) { return false; } int[][] dp = new int[nums.length][nums.length]; int sum = 0; for (int num : nums) { sum += num; } for (int i = 0; i < nums.length; i++) { dp[i][i] = nums[i]; } for (int i = nums.length - 2; i >= 0; i--) { for (int j = i + 1; j < nums.length; j++) { dp[i][j] = Math.max(nums[i] - dp[i + 1][j], nums[j] - dp[i][j - 1]); } } return dp[0][nums.length - 1] >= 0; }}
0 0
- [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
- 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
- TCP/IP学习笔记<二>
- netty与rabbitmq整合之netty传输大文件解决
- 17 - 05 - 01 Web安全(28)
- MFC修改界面和控件颜色
- 利用iso镜像做本地yum源安装KVM
- [LeetCode]486. Predict the Winner
- 17 - 05 - 02 Web安全(29)
- Cocos2d-x 3.X 里的回调函数及其参数适配
- 递归函数工作原理
- 输入菱形星号 C语言 自定义行数n
- webpack + react 优化:缩小js包体积
- 整除的尾数 HDU - 2099
- MySQL1
- 17_1_24 笔记之android 动画 1