LeetCode 877. Stone Game

题目链接:Stone Game - LeetCode

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.

设dp[l][r]为从l~r这一段能获得的最大分
则如果选择最左段的石子piles[l],有dp[l][r] = piles[l]-dp[l+1][r](因为下一步对手也会从[l+1]~[r]选择最大分,所以要减dp[l+1][r]);
如果选择最右段的石子piles[r],有dp[l][r] = piles[r]-dp[l][r-1]

根据表达式看出l要从后往前遍历,保证遍历到状态l时的计算结果依据的是状态l+1完成计算后的结果
根据表达式看出r要从后往前遍历,保证遍历到状态r时的计算结果依据的是状态r-1完成计算后的结果

class Solution {
public:
    bool stoneGame(vector<int>& piles) {
        int n = piles.size();
        vector<vector<int>>dp(n+1, vector<int>(n+1, 0));
        for(int l = n - 1; l >= 0; l--)
            for(int r = l + 1; r < n; r ++){
                int left = piles[l] - dp[l+1][r];
                int right = piles[r] - dp[l][r-1];
                dp[l][r] = max(left, right);
            }
        return dp[0][n - 1] >= 0;
    }
};

老实说这个官方题解看不太懂,记录一下吧

class Solution {
public:
    bool stoneGame(vector<int>& piles) {
        int N = piles.size();

        // dp[i+1][j+1] = the value of the game [piles[i], ..., piles[j]]
        int dp[N+2][N+2];
        memset(dp, 0, sizeof(dp));

        for (int size = 1; size <= N; ++size)
            for (int i = 0, j = size - 1; j < N; ++i, ++j) {
                int parity = (j + i + N) % 2;  // j - i - N; but +x = -x (mod 2)
                if (parity == 1)
                    dp[i+1][j+1] = max(piles[i] + dp[i+2][j+1], piles[j] + dp[i+1][j]);
                else
                    dp[i+1][j+1] = min(-piles[i] + dp[i+2][j+1], -piles[j] + dp[i+1][j]);
            }

        return dp[1][N] > 0;
    }
};

方法二:数学优化才是最强的降维打击
可以容易地证明亚历克斯总能赢得比赛:Solution:Stone Game - LeetCode

class Solution {
public:
   bool stoneGame(vector<int>& piles) {
       return true;
   }
};

你可能感兴趣的:(动态规划,博弈,LeetCode,LeetCode,题解,C++版)