welcome to my blog
LeetCode 877. Stone Game (Java版; Meidum)
题目描述
Alex and Lee play a game with piles of stones. There are an even number of piles arranged in a row,
and each pile has a positive integer number of stones piles[i].
The objective of the game is to end with the most stones. The total number of stones is odd, so there
are no ties.
Alex and Lee take turns, with Alex starting first. Each turn, a player takes the entire pile of stones
from either the beginning or the end of the row. This continues until there are no more piles left,
at which point the person with the most stones wins.
Assuming Alex and Lee play optimally, return True if and only if Alex wins the game.
Example 1:
Input: [5,3,4,5]
Output: true
Explanation:
Alex starts first, and can only take the first 5 or the last 5.
Say he takes the first 5, so that the row becomes [3, 4, 5].
If Lee takes 3, then the board is [4, 5], and Alex takes 5 to win with 10 points.
If Lee takes the last 5, then the board is [3, 4], and Alex takes 4 to win with 9 points.
This demonstrated that taking the first 5 was a winning move for Alex, so we return true.
Note:
2 <= piles.length <= 500
piles.length is even.
1 <= piles[i] <= 500
sum(piles) is odd.
第一次做; 动态规划 核心: 1) dp[i][j][0]表示先手在[i,j]上拥有石子数量的最大值; dp[i][j][1]表示后手在[i,j]上拥有石子数量的最大值 2)状态转移方程比较复杂 3) 斜着遍历矩阵
class Solution {
public boolean stoneGame(int[] piles) {
/*
dp[i][j][0]表示玩家A在[i,j]上能得到的最大值
dp[i][j][1]表示玩家B在[i,j]上能得到的最大值
先手和后手的角色切换?
dp[i][j][0] = max(piles[i]+dp[i+1][j][1], piles[j]+dp[i][j-1][1])
*/
int n = piles.length;
int[][][] dp = new int[n][n][2];
for(int i=0; i<n; i++){
dp[i][i][0] = piles[i];
dp[i][i][1] = 0;
}
//轮次
for(int round = 1; round<=n-1; round++){
//从第0行开始; 横坐标
for(int i=0; i<n-round; i++){
//纵坐标
int j = i + round;
//先手的选择
//选择piles[i]的话, 就只能获取[i+1][j]上后手的最大值了, 因为自己无法作为先手在[i+1,j]上进行选择了
int left = piles[i]+dp[i+1][j][1];
//选择piles[j]的话, 就只能获取[i][j-1]上后手的最大值了, 因为自己无法作为先手在[i,j-1]上进行选择了
int right = piles[j]+dp[i][j-1][1];
if(left > right){
//先手
dp[i][j][0] = left;
//后手怎么选? 获取[i+1,j]上先手能获取的最大值作为自己在[i,j]上的最优解
dp[i][j][1] = dp[i+1][j][0];
}
//后手
else{
dp[i][j][0] = right;
dp[i][j][1] = dp[i][j-1][0];
}
}
}
return dp[0][n-1][0] > dp[0][n-1][1];
}
}