【leetcode每日刷题】【dp】877. Stone Game

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:

  1. 2 <= piles.length <= 500
  2. piles.length is even.
  3. 1 <= piles[i] <= 500
  4. sum(piles) is odd.
class Solution {
    public boolean stoneGame(int[] piles) {
        int N = piles.length;
        int[][] dp = new int[N+2][N+2];
        for(int size=1; size<=N; ++size){
            for(int i=0; i+size<=N; ++i){
                int j = i+size-1;
                int count = (j+i+N)%2;
                if(count == 1){
                    dp[i+1][j+1] = Math.max(piles[i]+dp[i+2][j+1], piles[j]+dp[i+1][j]);
                }else{
                    dp[i+1][j+1] = Math.min(-piles[i]+dp[i+2][j+1], -piles[j]+dp[i+1][j]);
                }
            }
        }
        return dp[1][N] > 0;
    }
}

石子问题:使用动态规划求解

让我们改变游戏规则,使得每当lee得分时,都会从alex的分数中扣除。

令 dp(i, j) 为alex可以获得的最大分数,其中剩下的堆中的石子数是 piles[i], piles[i+1], ..., piles[j]。这在比分游戏中很自然:我们想知道游戏中每个位置的值。

我们可以根据 dp(i + 1,j) 和 dp(i,j-1) 来制定 dp(i,j) 的递归,我们可以使用动态编程以不重复这个递归中的工作。(该方法可以输出正确的答案,因为状态形成一个DAG(有向无环图)。)

当剩下的堆的石子数是 piles[i], piles[i+1], ..., piles[j] 时,轮到的玩家最多有 2 种行为。

可以通过比较 j-i和 N modulo 2 来找出轮到的人。

如果玩家是alex,那么它将取走 piles[i] 或 piles[j] 颗石子,增加它的分数。之后,总分为 piles[i] + dp(i+1, j) 或 piles[j] + dp(i, j-1);我们想要其中的最大可能得分。

如果玩家是lee,那么它将取走 piles[i] 或 piles[j] 颗石子,减少alex这一数量的分数。之后,总分为 -piles[i] + dp(i+1, j) 或 -piles[j] + dp(i, j-1);我们想要其中的最小可能得分。

数学分析

因为石头的数量是奇数,因此只有两种结果,输或者赢。

alex先开始拿石头,随便拿!然后比较石头数量:

  1. 如果石头数量多于对手,赢了;
  2. 如果石头数量少于对手,自己拿石头的顺序和对手拿石头的顺序对调(因为是偶数堆石头,所以可以全部对调),还是赢。

结果总是返回true, 所以可以直接  return true

你可能感兴趣的:(leetcode刷题,java)