2025年10月7日 星期二

適合初學者的暴力法-背包

import itertools weights = [2, 3, 4, 5] values = [3, 4, 5, 6] capacity = 8 vmax = 0 smax = [] for s in range(len(weights)+1): for c in itertools.combinations(weights, s): if sum(c)<=capacity: # print(c) v = 0 for j in c: v =v+ values[weights.index(j)] # print(v) if v > vmax: vmax = v smax = c print(vmax,smax) # Output: # 10 (3, 5)

沒有留言:

張貼留言