动态规划

题目:从面额为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}")  
    
      


    
原文地址:https://www.cnblogs.com/linyihai/p/10427406.html