python - 解可被 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, m, n)
print (x)
# This code is contributed by Afzal Ansari
我不明白如何获得解决方案的数量并使用 if 来保持解决方案只能被 3 整除。面试官从未给我答案,我开始怀疑这是否是一项不可能完成的任务。
解决方案
推荐阅读
- azure - 错误:部署参数使用区分大小写的名称。错误参数名称:名称。(ARM 模板部署)
- linux - 如何将参数传递到 shell 脚本中的文件中?
- apache-spark - 根据 pyspark 中的列和窗口期中的过滤条件计算平均值
- javascript - 如何用 JS 创建两个类似的增量游戏升级
- java - 方法设计模式 - 强制所有方法遵循一个模式
- elixir - Elixir 中与 Ruby 中的实例变量有什么相似的用法?
- android - Android 应用程序在改造拦截器中因 SocketTimeoutException 而崩溃
- python - txt 文件作为输入以反序列化 protobuff python 中的数据,无法以正确格式读取数据
- java - Android 中的单选按钮和单选组
- hash - Xamarin ios,SSL pinning:计算的公钥哈希不匹配