Title Description
Alex and Lee heap with a few stones in the game. Even-numbered stones piled in a row , stone pieces are positive integers each pile piles[i]
.
Who's Got the game with the most stones to determine the winner. The total number of stones is odd, there is no draw.
Alex and Lee take turns, Alex first start. Each turn, players take away the whole pile of stone from the beginning or end of the line. This situation continued until no more stones pile, at which point most of the hands of stone wins.
Alex Lee assumptions and play the best level, when Alex returned to win the game true
, when Lee returned to win the game false
.
输入:[5,3,4,5]
输出:true
Problem-solving ideas : solution to this question (and even codes) and 486 questions a hair the same. Look here what labuladong Gangster " dynamic programming ideas to solve common problems of the Game " button.
Reference Code
class Solution {
public:
bool stoneGame(vector<int>& piles) {
int length = piles.size();
if(length <= 1)
return true;
vector<vector<int> > dp(length, vector<int>(length, 0));
for(int i = 0; i < length; i++)
dp[i][i] = piles[i];
for(int i = length-2; i >= 0; i--){
for(int j = i+1; j < length; j++){
dp[i][j] = max(piles[i] - dp[i+1][j], piles[j] - dp[i][j-1]);
}
}
return dp[0][length-1] >= 0;
}
};