0877. Stone Game - kumaeki/LeetCode GitHub Wiki
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: piles = [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.
Constraints:
- 2 <= piles.length <= 500
- piles.length is even.
- 1 <= piles[i] <= 500
- sum(piles) is odd.
解法1
遍历,用二维数组储存中间结果.
class Solution {
// alex得分
int pointA = 0;
// Lee得分
int pointL = 0;
// mat[i][j]表示在剩余从i到j区间时, alex能否赢
Boolean[][] mat;
public boolean stoneGame(int[] piles) {
int len = piles.length;
mat = new Boolean[len][len];
return helper(piles, 0, len - 1, true);
}
// 判断是否alex能赢Lee
private boolean helper(int[] p, int start, int end, boolean isAlex){
if(mat[start][end] != null)
return mat[start][end] && isAlex;
if(start == end){
if(isAlex) pointA += p[start];
else pointL += p[start];
if(pointA > pointL){
mat[start][end] = isAlex;
return true;
}
if(isAlex) pointA -= p[start];
else pointL -= p[start];
mat[start][end] = !isAlex;
return false;
}
if(isAlex) pointA += p[start];
else pointL += p[start];
if(helper(p, start + 1, end, !isAlex)){
mat[start][end] = isAlex;
return true;
}
if(isAlex) pointA -= p[start];
else pointL -= p[start];
if(isAlex) pointA += p[end];
else pointL += p[end];
if(helper(p, start, end - 1, !isAlex)){
mat[start][end] = isAlex;
return true;
}
if(isAlex) pointA -= p[end];
else pointL -= p[end];
mat[start][end] = !isAlex;
return false;
}
}
解法2
其实可以用mat来保存比对手多拿的数量.
class Solution {
public boolean stoneGame(int[] p) {
int n = p.length;
// dp[i][j]表示在p[i,j]中比对手多拿的石头的数量
int[][] dp = new int[n][n];
for (int i = 0; i < n; i++) dp[i][i] = p[i];
for (int d = 1; d < n; d++)
for (int i = 0; i < n - d; i++)
dp[i][i + d] = Math.max(p[i] - dp[i + 1][i + d], p[i + d] - dp[i][i + d - 1]);
return dp[0][n - 1] > 0;
}
}
解法3
alex肯定赢.
class Solution {
public boolean stoneGame(int[] p) {
return true;
}
}