leetcode 877. Stone Game | 877. 石子游戏(递归/动态规划/数学解法)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 877. Stone Game | 877. 石子游戏(递归/动态规划/数学解法)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目
https://leetcode.com/problems/stone-game/
題解
搜了一下 stone game,結(jié)果。。
進(jìn)入正題:
一開始寫了個(gè)遞歸,超時(shí)了。沒想出怎么寫 dp,看了答案之后寫的。
整體草稿:
方法1:遞歸(超時(shí))
class Solution {public boolean stoneGame(int[] piles) {int target = 0;for (int n : piles) {target += n;}target /= 2;return pick(0, piles.length - 1, piles, 0, target, true);}// 所有無后效性的遞歸都可以改寫成dp?本題有后效性嗎?public boolean pick(int L, int R, int[] piles, int sum, int target, boolean turn) {if (sum > target) return true;if (L == R) {return false;} else if (turn) {return pick(L + 1, R, piles, sum + piles[L], target, false) || pick(L, R - 1, piles, sum + piles[R], target, false);} else {return pick(L + 1, R, piles, sum, target, true) || pick(L, R - 1, piles, sum, target, true);}} }方法2:動(dòng)態(tài)規(guī)劃
參考:官方題解,有動(dòng)圖演示,比較好懂一些
方法3:數(shù)學(xué)方法
總結(jié)
以上是生活随笔為你收集整理的leetcode 877. Stone Game | 877. 石子游戏(递归/动态规划/数学解法)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 419. Battle
- 下一篇: leetcode 427. Constr