[leetcode]877. Stone Game
Analysis
paper 被拒了,改了一个礼拜,心塞,然后回家过暑假了—— [我胡汉三又回来了!]
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.
虽然题目出的有bug,就是不管什么情况都是Alex赢,所以只要返回true就能AC,但是我们还是按照一般的动态规划问题解决。
我讨厌动态规划啊!参考了大神们的解法,这个博客解释的比较清楚:
https://blog.youkuaiyun.com/androidchanhao/article/details/81271077
Implement
class Solution {
public:
bool stoneGame(vector<int>& piles) {
int len = piles.size();
vector<vector<int> > dp(len, vector<int>(len, 0));
for(int i=0; i<len; i++)
dp[i][i] = piles[i];
for(int dis=1; dis<len; dis++){
for(int i=0; i<len-dis; i++)
dp[i][i+dis] = max(piles[i]-dp[i+1][i+dis], piles[i+dis]-dp[i][i+dis-1]);
}
return dp[0][len-1]>0;
}
};