最小硬幣找零問題


給定一個硬幣列表 C(c1, c2, ……Cn) 和一個值 V。現在的問題是如何使用最少的硬幣來湊夠 V。

注意 − 假設 C 中的硬幣數量是無限的

在此問題中,我們會考慮給定一組不同的硬幣 C{1, 2, 5, 10},每種型別的硬幣數量都是無限的。為了湊夠所需的值,我們將嘗試取儘可能少的任何型別的硬幣。

例如,對於值 22,我們將選擇 {10, 10, 2},共 3 枚硬幣,作為最少數量。

此演算法的時間複雜度為 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+ 瀏覽量

開啟你的職業生涯

完成課程獲得認證

開始學習
ADVERTISEMENT