我正试图找出一种方法来解决(在c ++中),给定一个价格不变的物品清单,如果他们有X金额,一个人可以购买多少种X物品。
到目前为止,我已经尝试使用嵌套for循环来尝试强制解决方案,但是,我觉得我可能会错过一个我似乎无法看到的非常简单的解决方案。
非常感谢任何帮助。 感谢。
答案 0 :(得分:0)
这与常见的编程问题非常类似:“你可以用多少种方式将Y种类型的硬币与Z值组合起来制作X美元”,即用Y币类型改变X美元。
这是一个可以移植到C ++的通用解决方案:
I = list of items SORTED from highest to lowest price
N = number of items bought so far
M = money left
S = money to start
function shop(I, N, M, S):
if M < 0: return 0 //we bought something illegally!
if M == 0:
//If we have no money, we've bought all we could.
//Check our condition that num items N = starting money S
return 1 if N == S, else 0
if I is empty:
return 0 //no more item combos, no way to buy things.
else:
newI = I with first element removed
//Every time we want to buy stuff, we have two options:
//1. buy something of highest value and subtract money
//2. Shop ignoring the next highest value item
return shop(newI, N, M, S) + shop(I, N+1, M-(cost of first item), S)
使用X美元,您可以从电话开始:
shop(I, 0, X, X)