class Solution(object):
def canIWin(self, maxChoosableInteger, desiredTotal):
"""
:type maxChoosableInteger: int
:type desiredTotal: int
:rtype: bool
"""
if sum(range(1,maxChoosableInteger+1))<desiredTotal:
return False
self.memo=dict()
return self.helper(range(1,maxChoosableInteger+1),desiredTotal)
def helper(self,array,desiredTotal):
array_hash=str(array)
#this is memoization, if this subproblem has already been calculated then return directly
if array_hash in self.memo:
return self.memo[array_hash]
#this is the base case of the problem. if it is my turn and the max number in the array is enough to reach the desiredTotal , then i can force a win by simply picking this max number
if array[-1]>=desiredTotal:
self.memo[array_hash]=True
return True
#pick a number, if the opponent can't force a win with the rest, that means i can force a win with picking this number
for i in xrange(len(array)):
if not self.helper(array[:i]+array[i+1:],desiredTotal-array[i]):
self.memo[array_hash]=True
return True
#if there is no number that i can pick to force a win, then this array, total combination is false.
self.memo[array_hash]=False
return False
464. Can I Win
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 2014年09月23日 9695 愿你纵深一跃,不惧深渊。愿风暴降临,你岸堤永固。愿人群声嘶力竭,呼喊你名。愿众人...