Description
There are n coins in a line. Two players take turns to take one or two coins from right side until there are no more coins left. The player who take the last coin wins.
Could you please decide the first play will win or lose?
Have you met this question in a real interview? Yes
Example
n = 1
, return true
.
n = 2
, return true
.
n = 3
, return false
.
n = 4
, return true
.
n = 5
, return true
.
Challenge
O(n) time and O(1) memory
class Solution:
"""
@param n: An integer
@return: A boolean which equals to true if the first player will win
"""
def firstWillWin(self, n):
# write your code here
dp = [False for i in xrange(n + 1)]
visited = [0 for i in xrange(n + 1)]
if n == 1 or n == 2 or n == 4:
return True
elif n == 0 or n == 3:
return False
#1.初始化
dp[0] = False
dp[1] = True
dp[2] = True
dp[3] = False
dp[4] = True
visited[0] = 1
visited[1] = 1
visited[2] = 1
visited[3] = 1
visited[4] = 1
return self.memorySearch(n,dp,visited)
def memorySearch(self,i,dp,visited):
if visited[i] == 1:
return dp[i]
dp[i] = ( ( self.memorySearch(i - 2,dp,visited) and self.memorySearch(i - 3,dp,visited) ) or
( self.memorySearch(i -3,dp,visited) and self.memorySearch(i -4,dp,visited) ) )
visited[i] = 1
return dp[i]