1 Star 0 Fork 0

yuhang2__2/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
form-largest-integer-with-digits-that-add-up-to-target.py 1.87 KB
一键复制 编辑 原始数据 按行查看 历史
# 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))
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yuhang2__2/LeetCode-Solutions.git
git@gitee.com:yuhang2__2/LeetCode-Solutions.git
yuhang2__2
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助