bottom-up dp solution
class Solution(object):
def getMoneyAmount(self, n):
"""
:type n: int
:rtype: int
"""
dp=[[0]*(n+1) for _ in xrange(n+1)]
for lo in xrange(n,0,-1):
for hi in xrange(lo+1,n+1):
dp[lo][hi]=min(x+max(dp[lo][x-1],dp[x+1][hi]) for x in xrange(lo,hi))
return dp[1][n]
class Solution(object):
def getMoneyAmount(self, n):
"""
:type n: int
:rtype: int
"""
class helper(dict):
def __missing__(self,(lo,hi)):
if lo>=hi:
return 0
ret=self[lo,hi]=min(x+max(self[lo,x-1],self[x+1,hi]) for x in range(lo,hi))
return ret
return helper()[1,n]
网友评论