There is n coins in a line. Players take turns to take one or both coins from right side until there is no more coins left. The player who has the last coin wins.
Could decide the first play would win or lose?
This is the DP problem of a class of game.
The basic solution to the game problem is:
State: Defines the status of one person.
Function: Consider the status of two people to do the update, that is, according to a relationship against each other to make decisions.
The game class topic is suitable from the large state to the small state recursion, is very suitable for the memory search. But the problem itself is relatively simple, can have been bottom-up to do.
This analysis F[i] for the remaining I coin when the initiator can win. We consider a recursive state. The initiator in F[i] can win, that is, he took the last one or two coins. This is f[i-1] the latter f[i-2] when the hand wins, so there is a recursive relationship f[i] =!f[i-1]| |! F[i-2]
Initialization, there are 0 coins left when the initiator must lose. There are 1 or 2 coins left to win. But what does the final result take? There are 0 coins left, or n pieces. Actually we are from still have n coin, consider this time of game state consideration, so is f[n]. The code is as follows:
classSolution:#@param n:an Integer #@return: A Boolean which equals to True if the first player would win defFirstwillwin (self, n):ifN <=0:returnFalseifN <= 2: returnTrue F= [False] * (n+1) f[1] =True f[2] =True forIinchXrange (2,n+1): F[i]= ( notF[I-1])or( notF[i-2]) returnF[n]
Coins in a line