斐波那契演算法舉例(iterative Fibonacci algorithm)

來源:互聯網
上載者:User

// count_change.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

/*-------------------------------------------------------------
執行個體:要想得到一個迭代的斐波那契演算法需要一點點智慧。
給了半美元、四分之一美元、10美分、5美分、1美分的硬幣,將1美元換成零錢,一共有多少中不同的方式?
更一般的問題時,給定了任意數量的現金,我們能寫出一個程式,計算出所有換零錢方式的種數嗎?
採用遞迴過程,這一過程有一種很簡單的解法。假定我們所考慮的可用硬幣類型種類排了某種順序,於是就有下面的關係:
將總數為a的現金換成n中硬幣的不同方式的數目等於
1.將現金數a換成除第一種硬幣之外的所有其它硬幣的不同方式數目,加上
2.將現金數a-d換成所有種類的硬幣的不同方式數目,其中的d是第一種硬幣的幣值。

---------------------------------------------------------------*/
int first_denomination(int kinds_of_coins)
{
 if (1 == kinds_of_coins)
 {
  return 1;
 }
 else if(2 == kinds_of_coins)
 {
  return 5;
 }
 else if(3 == kinds_of_coins)
 {
  return 10;
 }
 else if(4 == kinds_of_coins)
 {
  return 25;
 }
 else if(5 == kinds_of_coins)
 {
  return 50;
 }
}

int cc(int amount, int kinds_of_coins)
{
 if (0 == amount)
 {
  return 1;
 }
 else if ((amount < 0) || (0 == kinds_of_coins))
 {
  return 0;
 }
 else
 {
  return ( ( cc(amount, kinds_of_coins-1) )+
     ( cc(amount-first_denomination(kinds_of_coins), kinds_of_coins))
     );
 }
}

int _tmain(int argc, _TCHAR* argv[])
{
 int n = cc(100, 5);
 return 0;
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.