877. Stone Game(python+cpp)

题目:

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.

解释:
动态规划,dp数组记录分数~
解法1:
动态规划
dp[i][j]表示piles范围是piles[i]~piles[j]时候,此时选择的人可以比对手最多能多拿多少,此时选择的人可以拿piles[i]或者piles[j]
1.拿了piles[i],那么dp[i][j]=piles[i]-dp[i+1][j]
2.拿了piles[j],那么dp[i][j]=piles[j]-dp[i][j-1]
所以转移公式是dp[i][j]=max(piles[i]-dp[i+1][j],piles[j]-dp[i][j-1])
最终返回dp[0][n-1](因为Alex是先手)
dp[i][i]=piles[i]
解法2:
因为石头堆的数目是偶数,这就导致Alex同学可以取走所有奇数堆或者所有偶数堆,如果由于最终的和是奇数,所以sum(odd)>sum(even)或者sum(even)>sum(odd),哪一类大就取哪一类,所以Alex同学一定能赢
解法1,python代码:

class Solution(object):
    def stoneGame(self, piles):
        """
        :type piles: List[int]
        :rtype: bool
        """
        n=len(piles)
        dp=[[0 for i in range(n)] for j in range(n)]
        for i in range(n):
            dp[i][i]=piles[i]
        for d in range(1,n):
            for i in range(n-d):
                dp[i][i+d]=max(piles[i]-dp[i+1][i+d],piles[i+d]-dp[i][i+d-1])
        return dp[0][n-1]>0

解法2,python代码:

class Solution(object):
    def stoneGame(self, piles):
        """
        :type piles: List[int]
        :rtype: bool
        """
        return True 

c++代码:

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

总结:

你可能感兴趣的:(LeetCode)