python - leetcode 硬币找零问题没有给出正确的结果
问题描述
我正在编写代码来解决这个问题,下面是我的代码,不知何故我看到结果是正确的,直到 for 循环结束,但是函数返回后它没有执行正确的结果值,见下面的日志打印,有人可以帮忙吗?谢谢!
https://leetcode.com/problems/coin-change/
"""
sort the coins to start with coin that has largest value;
then loop through possible number of that coins we could put,
and use dfs to go through other possible coin types
"""
def coinChange(self, coins, amount):
# write your code here
coins.sort()
coins=coins[::-1]
n=len(coins)
res=100000000000000
def getcom(i, coins, amount,count, res):
if amount==0:
res=min(res, count)
print("res: ", res)
if i==n:
return
coin=coins[i]
print("coin:", coins[i])
k=amount//coin
print("k:", k)
for j in range(k, -1, -1):
if count+j>res:
break
getcom(i+1, coins, amount-k*coin, count+k, res)
getcom(0,coins, amount, 0,res)
return res
testcase:Input: coins = [1, 2, 5], amount = 11
should Output: 3
解释:11 = 5 + 5 + 1
my stdout
coin: 5
k: 2
coin: 2
k: 0
coin: 1
k: 1
res: 3
res: 3
coin: 2
k: 0
coin: 1
k: 1
res: 3
res: 3
coin: 2
k: 0
coin: 1
k: 1
res: 3
res: 3
----------
my output: 100000000000000
解决方案
res
在方法调用中被修改但从未返回。
递归计算的结果不会传回调用堆栈。您需要添加一些return
语句。
"""
sort the coins to start with coin that has largest value;
then loop through possible number of that coins we could put,
and use dfs to go through other possible coin types
"""
def coinChange(coins, amount):
# write your code here
coins.sort()
coins=coins[::-1]
n=len(coins)
res=100000000000000
def getcom(i, coins, amount,count, res):
#nonlocal res
if amount==0:
res=min(res, count)
print("res: ", res)
if i==n:
return res
coin=coins[i]
print("coin:", coins[i])
k=amount//coin
print("k:", k)
for j in range(k, -1, -1):
if count+j>res:
break
return getcom(i+1, coins, amount-k*coin, count+k, res)
res = getcom(0,coins, amount, 0,res)
return res
print(coinChange([1,2,5], 11))
输出:
coin: 5
k: 2
coin: 2
k: 0
coin: 1
k: 1
res: 3
3
推荐阅读
- django - 在为 Django 模型创建自动主键字段时是否需要指定 default=django.utils.timezone.now
- flutter - 当上下文从 init 方法传递给 Provider 时,Flutter 会抛出错误
- c - OpenSSL C Cryptopals 挑战赛7
- javascript - is there a way to break list into columns using VueJs?
- visual-studio - C++ no instance of constructor matches the argument list argument types are: (std::string, double)
- c++ - Why in C++ do static_cast
of negative numbers differ if the number is constant or not - c# - 如何跟踪和保存 Hololens 1 的头部注视光标位置文件
- javascript - 使用firebase调用时如何在forEach中使用异步调用
- c - 为什么结构内存用随机字符初始化?(嵌入式)
- python - 发现样本数量不一致的输入变量:[24, 25]