如何解决解决方案可被 3 整除的硬币找零问题动态规划
我最近参加了一次求职面试,面试官让我调整硬币找零问题,以便只返回可被 3 整除的解决方案。
问题不得不使用动态规划的方式解决硬币找零问题,我有点卡住了。我已经使用生成器解决了这个问题,但是对于较大的数字来说太慢了。
显然要检查一个数是否可以被三整除
number%3==0
然后给定来自 https://www.geeksforgeeks.org/coin-change-dp-7/
的这个模板# Dynamic Programming Python implementation of Coin
# Change problem
def count(S,m,n):
# table[i] will be storing the number of solutions for
# value i. We need n+1 rows as the table is constructed
# in bottom up manner using the base case (n = 0)
# Initialize all table values as 0
table = [0 for k in range(n+1)]
# Base case (If given value is 0)
table[0] = 1
# Pick all coins one by one and update the table[] values
# after the index greater than or equal to the value of the
# picked coin
for i in range(0,m):
for j in range(S[i],n+1):
table[j] += table[j-S[i]]
return table[n]
# Driver program to test above function
arr = [50,20,10,1] # list of coins
m = len(arr)
n = 10000 # amount
x = count(arr,n)
print (x)
# This code is contributed by Afzal Ansari
我不明白如何获得解决方案的数量并使用 if 只保持解决方案可被 3 整除。 面试官从来没有给我答案,我开始怀疑这是不是不可能完成的任务。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。