代码拉取完成,页面将自动刷新
# Time: O(t)
# Space: O(t)
class Solution(object):
def largestNumber(self, cost, target):
"""
:type cost: List[int]
:type target: int
:rtype: str
"""
dp = [0]
for t in xrange(1, target+1):
dp.append(-1)
for i, c in enumerate(cost):
if t-c < 0 or dp[t-c] < 0:
continue
dp[t] = max(dp[t], dp[t-c]+1)
if dp[target] < 0:
return "0"
result = []
for i in reversed(xrange(9)):
while target >= cost[i] and dp[target] == dp[target-cost[i]]+1:
target -= cost[i]
result.append(i+1)
return "".join(map(str, result))
# Time: O(t)
# Space: O(t)
class Solution2(object):
def largestNumber(self, cost, target):
"""
:type cost: List[int]
:type target: int
:rtype: str
"""
def key(bag):
return sum(bag), bag
dp = [[0]*9]
for t in xrange(1, target+1):
dp.append([])
for d, c in enumerate(cost):
if t < c or not dp[t-c]:
continue
curr = dp[t-c][:]
curr[~d] += 1
if key(curr) > key(dp[t]):
dp[-1] = curr
if not dp[-1]:
return "0"
return "".join(str(9-i)*c for i, c in enumerate(dp[-1]))
# Time: O(t^2)
# Space: O(t^2)
class Solution3(object):
def largestNumber(self, cost, target):
"""
:type cost: List[int]
:type target: int
:rtype: str
"""
dp = [0]
for t in xrange(1, target+1):
dp.append(-1)
for i, c in enumerate(cost):
if t-c < 0:
continue
dp[t] = max(dp[t], dp[t-c]*10 + i+1)
return str(max(dp[t], 0))
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。