tomdapchai
Senior Member
Python:
class Solution:
def winnerSquareGame(self, n: int) -> bool:
def isSquare(n: int) -> bool:
return math.isqrt(n) ** 2 == n
# pre compute the list for each number from 1->n
squares = defaultdict(list[int])
squares[0] = []
for i in range(1, n + 1):
squares[i] = copy.deepcopy(squares[i - 1])
if isSquare(i):
squares[i].append(i)
# the optimal strategy: player try to have the next turn of the them the piles would have a square number of it
# means each player will try to make the next turn not have a square number
dp = [False] * (n + 1)
for i in range(1, n + 1):
if isSquare(i):
dp[i] = True
continue
result = False
for square in squares[i]:
if not isSquare(i - square):
result = result or (not dp[i - square])
dp[i] = result
return dp[n]

Update: tối ưu bằng cách k pre computed nữa
Python:
class Solution:
def winnerSquareGame(self, n: int) -> bool:
def isSquare(n: int) -> bool:
return math.isqrt(n) ** 2 == n
# the optimal strategy: player try to have the next turn of the them the piles would have a square number of it
# means each player will try to make the next turn not have a square number
dp = [False] * (n + 1)
for i in range(1, n + 1):
if isSquare(i):
dp[i] = True
continue
k = 1
while k * k < i:
if not isSquare(i - k * k) and not dp[i - k * k]:
dp[i] = True
break
k += 1
return dp[n]
Sửa lần cuối:

