动态规划

题目:从面额为2,3,7的钱币中,找出能凑够100块的最小钱币数。

思考



import time
money_type = [2, 3, 7]
total = 100
ret = {}
st = time.time()
for i in range(1, total + 1):
    tmp = []
    for mt in money_type:
        if mt == i:
            tmp.append((1, [mt]))
        else:
            if i - mt in ret:
                count, zuhe = ret[i - mt]
                count += 1
                zuhe = zuhe[:]
                zuhe.append(mt)
                tmp.append((count, zuhe))
            if mt == i:
                tmp.append((1, [mt]))
    if tmp:
        ret[i] = min(tmp)
print(i, ret.get(i, ()))
print(f"total time {time.time() - st}")
import sys
sys.setrecursionlimit(1000000)
st = time.time()
# 递归求导,100时,递归求导极慢
def my_func(total, zuhe=[]):
    if total in money_type:
        zuhe.append(str(total))
        print("可能组合为:"+",".join(zuhe))
        return 1
    tmp = []
    for mt in money_type:
        rest = total - mt
        if rest >= min(money_type):
            new_zuhe = zuhe[:]
            new_zuhe.append(str(mt))
            count = my_func(rest, new_zuhe) + 1
            tmp.append(count)
        else:
            continue
    if tmp:
        return min(tmp)
    else:
        return 0
   

print("最小取值为"+ str(my_func(total)))
print(f"total time {time.time() - st}")  
    
      


    
posted @   yihailin  阅读(111)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
点击右上角即可分享
微信分享提示