forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
can-i-win.py
30 lines (25 loc) · 1004 Bytes
/
can-i-win.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
# Time: O(n!)
# Space: O(n)
class Solution(object):
def canIWin(self, maxChoosableInteger, desiredTotal):
"""
:type maxChoosableInteger: int
:type desiredTotal: int
:rtype: bool
"""
def canIWinHelper(maxChoosableInteger, desiredTotal, visited, lookup):
if visited in lookup:
return lookup[visited]
mask = 1
for i in xrange(maxChoosableInteger):
if visited & mask == 0:
if i + 1 >= desiredTotal or \
not canIWinHelper(maxChoosableInteger, desiredTotal - (i + 1), visited | mask, lookup):
lookup[visited] = True
return True
mask <<= 1
lookup[visited] = False
return False
if (1 + maxChoosableInteger) * (maxChoosableInteger / 2) < desiredTotal:
return False
return canIWinHelper(maxChoosableInteger, desiredTotal, 0, {})