leetcode-26双周赛-5399-数位成本和为目标值的最大数字
Posted 真不知道叫啥好
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-26双周赛-5399-数位成本和为目标值的最大数字相关的知识,希望对你有一定的参考价值。
题目描述:
提交:背包问题
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-数位成本和为目标值的最大数字的主要内容,如果未能解决你的问题,请参考以下文章
leetcode-26双周赛-5398-统计二叉树中好结点的数目
leetcode-26双周赛-5398-统计二叉树中好结点的数目