forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
divisor-game.py
44 lines (40 loc) · 1.23 KB
/
divisor-game.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# Time: O(1)
# Space: O(1)
class Solution(object):
def divisorGame(self, N):
"""
:type N: int
:rtype: bool
"""
# 1. if we get an even, we can choose x = 1
# to make the opponent always get an odd
# 2. if the opponent gets an odd, he can only choose x = 1 or other odds
# and we can still get an even
# 3. at the end, the opponent can only choose x = 1 and we win
# 4. in summary, we win if only if we get an even and
# keeps even until the opponent loses
return N % 2 == 0
# Time: O(n^3/2)
# Space: O(n)
# dp solution
class Solution2(object):
def divisorGame(self, N):
"""
:type N: int
:rtype: bool
"""
def memoization(N, dp):
if N == 1:
return False
if N not in dp:
result = False
for i in xrange(1, N+1):
if i*i > N:
break
if N % i == 0:
if not memoization(N-i, dp):
result = True
break
dp[N] = result
return dp[N]
return memoization(N, {})