我如何提高其运行时间
问题陈述:您将为您提供一个整数阵列硬币,代表代表不同宗派的硬币和代表总金额的整数数量。返回您需要弥补该金额的最少的硬币。如果硬币的任何组合无法弥补这笔钱,请返回-1。您可能会假设每种硬币的无限数量。
有没有办法使我的解决方案更快?
说明:DP [Curr_amount]存储我需要更多的硬币的最低数量才能达到目标量
def coinChange(self, coins: List[int], amount: int) -> int:
if amount == 0:
return 0
dp = {}
def backtrack(curr_amount):
if (curr_amount) in dp:
return dp[curr_amount]
if curr_amount == amount:
return 0
if curr_amount > amount:
return inf
for coin in coins:
if (curr_amount) not in dp:
dp[curr_amount] = inf
# Take the minimum number of coins needed given all the possible choices
dp[curr_amount] = min(dp[curr_amount], 1 + backtrack(curr_amount + coin))
return dp[curr_amount]
res = backtrack(0)
if res == inf:
return -1
return res
Problem Statement: You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. You may assume that you have an infinite number of each kind of coin.
Is there a way to make my solution faster?
Explanation: dp[curr_amount] stores the minimum number of how many more coins I would need to reach target amount
def coinChange(self, coins: List[int], amount: int) -> int:
if amount == 0:
return 0
dp = {}
def backtrack(curr_amount):
if (curr_amount) in dp:
return dp[curr_amount]
if curr_amount == amount:
return 0
if curr_amount > amount:
return inf
for coin in coins:
if (curr_amount) not in dp:
dp[curr_amount] = inf
# Take the minimum number of coins needed given all the possible choices
dp[curr_amount] = min(dp[curr_amount], 1 + backtrack(curr_amount + coin))
return dp[curr_amount]
res = backtrack(0)
if res == inf:
return -1
return res
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不确定如何
修复
自己的方式,但可以尝试查看是否可以加快加速。这是DP自下而上的方法:有点遵循@Joanis思想(灵感来自)。谢谢。
Not sure how to
fix
your way, but can try to see if this can speed up. It's DP bottom-up approach:It's kind of follow @joanis thought (inspired by). Thanks.
我建议您采用广度优先的搜索方法。
该想法如下:
in Coins
中的任何值c
,如果我们可以在s中达到值
步骤,然后我们可以在x
,则s+1
步骤中访问x+c
,对于硬币中的每个c
。因此,我们可以使用队列结构有效地将映射从目标扩展到最小步骤。
I would suggest the breadth-first search approach.
The idea is as follows:
c
incoins
can be reached in one stepx
ins
steps, then we can reachx+c
ins+1
steps, for eachc
in coins.So, we can expand the mapping from the target to the minimum steps efficiently by using the queue structure.