标签:src targe style com int cache lse class str
题目描述:
提交:背包问题
class Solution: def largestNumber(self, cost, target: int) -> str: dp = [[0 for _ in range(target + 1)] for _ in range(10)] def tmax(a,b): if not a: return b elif not a: return b elif int(b) > int(a): return b else: return a for i in range(10): for j in range(target+1): if i == 0 or j == 0: dp[i][j] = 0 elif cost[i-1] > j: dp[i][j] = dp[i-1][j] elif cost[i-1] == j: dp[i][j] = tmax(dp[i-1][j],str(i)) else: tmp = 0 if dp[i][j-cost[i-1]]: tmp = str(i)+str(dp[i][j-cost[i-1]]) dp[i][j] = tmax(dp[i-1][j],tmp) for j in range(9,-1,-1): if dp[j][target]: return dp[j][target] return "0"
优化:
class Solution: def largestNumber(self, cost: List[int], target: int) -> str: dp = [-1 for j in range(target + 1)] dp[0] = 0 for i in range(8, -1, -1): for j in range(cost[i], target + 1): if dp[j - cost[i]] < 0: continue dp[j] = max(dp[j], dp[j - cost[i]] * 10 + (i + 1)) if dp[target] >= 0: return str(dp[target]) else: return ‘0‘
方法二;自底向上
class Solution: def largestNumber(self, cost: List[int], tar: int) -> str: mi = min(cost) @lru_cache(None) def dp(target): # target 下的最大值 if target == 0: return 0 if target < mi: return -float(‘inf‘) res = -float(‘inf‘) for x in range(9): res = max(dp(target - cost[x])*10 + x + 1, res) return res res = dp(tar) return str(res) if res > 0 else "0"
leetcode-26双周赛-5399-数位成本和为目标值的最大数字
标签:src targe style com int cache lse class str
原文地址:https://www.cnblogs.com/oldby/p/12904819.html