877. Stone Game(DP)

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.

思路:先求出子问题即每两个石堆之间的差值,即Alex所能得到的比Lee多的部分,然后求连续三个石堆,四个。。,依次递推,最后求出原问题的解,dp[i][j]表示两石堆间Alex比Lee所能获得的多出来的部分。最后判断这个总差值是否大于0,若大于0则判定Alex赢。(注意dp[i][i]的初始化)

class Solution {
public:
    bool stoneGame(vector<int>& piles) {
        int n = piles.size();
        vector<vector<int> > dp(n,vector<int>(n,0));
        for(int i=0;i<n;i++){
            dp[i][i] = piles[i];
        }
        for(int i=1;i<n;i++){ //i is the distance of the neighbor
            for(int j=0;j<n-i;j++){
                dp[j][j+i] = max(abs(dp[j+1][j+i]-piles[j]),abs(dp[j][j+i-1]-piles[j]));
            }
        }
        if(dp[0][n-1]>0) return true;
        else return false;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章