最少硬币找零问题


给定一条硬币列表 C(c1, c2, ……Cn) 和一个值 V。现在的问题是使用最少的硬币数量来进行找零 V。

注意 − 假设有无限数量的硬币 C

在这个问题中,我们将考虑一组不同的硬币 C{1, 2, 5, 10},每种类型的硬币都有无限的数量。为了找零所需的价值,我们将尝试使用最少数量的任何类型的硬币。

例如,对于值 22 − 我们将选择 {10, 10, 2},最少 3 枚硬币。

此算法的时间复杂度 id O(V),其中 V 是值。

输入和输出

Input:
A value, say 47
Output:
Enter value: 47
Coins are: 10, 10, 10, 10, 5, 2

算法

findMinCoin(value)

输入 − 找零的值

输出 −硬币集合。

Begin
   coins set with value {1, 2, 5, 10}
   for all coins i as higher value to lower value do
      while value >= coins[i] do
         value := value – coins[i]
         add coins[i], in thecoin list
      done
   done
   print all entries in the coin list.
End

示例

#include<iostream>
#include<list>
#define COINS 4
using namespace std;

float coins[COINS] = {1, 2, 5, 10};

void findMinCoin(int cost) {
   list<int> coinList;

   for(int i = COINS-1; i>=0; i--) {
      while(cost >= coins[i]) {
         cost -= coins[i];
         coinList.push_back(coins[i]); //add coin in the list

      }
   }

   list<int>::iterator it;

   for(it = coinList.begin(); it != coinList.end(); it++) {
      cout << *it << ", ";
   }
}

main() {
   int val;
   cout << "Enter value: ";
   cin >> val;
   cout << "Coins are: ";
   findMinCoin(val);
   cout << endl;
}

输出

Enter value: 47
Coins are: 10, 10, 10, 10, 5, 2

更新于: 15-6月-2020

1K+ 次浏览

开启您的职业生涯

完成课程即可获得证书

开始
广告
© . All rights reserved.