DeepRest

Stone Game IV

Jan 21st, 2022 (edited)
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.74 KB | None | 0 0
  1. '''
  2. Bottom up DP
  3. dp[i]: is it possible to make a winning move with i stones left ?
  4. dp[i] = True €x: dp[x] = False for any x such that i-x is perfect square
  5. Base case: dp[0] is false
  6.  
  7. For a player to win he must have a move to make the opposite player lose
  8. If a player has no move to make opposite player lose then he lose, coz the other player will have a move to make him lose
  9. '''
  10. class Solution:
  11.     def winnerSquareGame(self, n: int) -> bool:
  12.         dp = [False]*(n+1)
  13.         for i in range(n+1):
  14.             if dp[i] == False:
  15.                 j = 1
  16.                 while (k := i + j*j)<=n:
  17.                     dp[k] = True
  18.                     j += 1
  19.             if dp[n] == True:
  20.                 return True
  21.         return dp[n]
Advertisement
Add Comment
Please, Sign In to add comment