Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何购买物品的组合_C++_Algorithm_Combinations - Fatal编程技术网

C++ 如何购买物品的组合

C++ 如何购买物品的组合,c++,algorithm,combinations,C++,Algorithm,Combinations,我试图找到一种方法来计算(在c++中),给定一个固定价格的物品列表,如果一个人有X美元,他可以通过多少种方式购买X数量的物品 到目前为止,我已经尝试使用嵌套for循环来尝试和强制执行一个解决方案,但是,我觉得我可能缺少一个我似乎看不到的非常简单的解决方案 任何帮助都将不胜感激。 谢谢。这与常见的编程问题非常相似:“有多少种方法可以将Y类型的硬币与Z值结合起来,从而生成X美元”,即用Y类型的硬币兑换X美元 下面是一个可以移植到C++的通用解决方案: I = list of items SORTED

我试图找到一种方法来计算(在c++中),给定一个固定价格的物品列表,如果一个人有X美元,他可以通过多少种方式购买X数量的物品

到目前为止,我已经尝试使用嵌套for循环来尝试和强制执行一个解决方案,但是,我觉得我可能缺少一个我似乎看不到的非常简单的解决方案

任何帮助都将不胜感激。
谢谢。

这与常见的编程问题非常相似:“有多少种方法可以将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)

这与常见的编程问题非常相似:“有多少种方法可以将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)

他们只能用Z美元购买物品a X次,或者他们可以购买物品a X次,物品b Y次。。。使用Z美元时,需要使用X美元的X件物品。例如,他们必须购买10件相当于10美元的物品。假设有Y种不同类型的物品。每件商品的价格都不到一美元。那你就可以这么做了!时间。他们只能用Z美元购买物品a X次,或者他们可以购买物品a X次,物品b Y次。。。使用Z美元时,需要使用X美元的X件物品。例如,他们必须购买10件相当于10美元的物品。假设有Y种不同类型的物品。每件商品的价格都不到一美元。那你就可以这么做了!时代。