c語言 跳臺階問題的解決方法
更新時(shí)間:2013年05月24日 09:29:20 作者:
本篇文章是對c語言中跳臺階問題的解決方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
題目:一個臺階總共有n級,如果一次可以跳1級,也可以跳2級。求總共有多少種跳法,并分析算法的時(shí)間復(fù)雜度。
答:用一個函數(shù)f(n)來表示n級臺階總的跳法。
1、只有1個臺階,則f(1) = 1;
2、有2個臺階,則f(2) = 2;
3、當(dāng)有n個臺階時(shí),如果第一次跳1級,有f(n-1)種跳法,如果第一次跳2級,有f(n - 2)種跳法,即f(n) = f(n-1) + f(n-2)。
即為Fibonacci序列。
#include "stdafx.h"
#include <iostream>
using namespace std;
//循環(huán)
int TotalStep(int n)
{
if (n <= 0)
{
return 0;
}
else if (1 == n || 2 == n)
{
return n;
}
int first = 1;
int second = 2;
int total = 0;
for (int i = 3; i <= n; i++)
{
total = first + second;
first = second;
second = total;
}
return total;
}
//遞歸
int RecurTotalStep(int n)
{
if (n <= 0)
{
return 0;
}
else if (n == 1 || n == 2)
{
return n;
}
else
{
return RecurTotalStep(n - 1) + RecurTotalStep(n - 2);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
cout<<TotalStep(20)<<endl;
cout<<RecurTotalStep(20)<<endl;
return 0;
}
運(yùn)行界面如下:
答:用一個函數(shù)f(n)來表示n級臺階總的跳法。
1、只有1個臺階,則f(1) = 1;
2、有2個臺階,則f(2) = 2;
3、當(dāng)有n個臺階時(shí),如果第一次跳1級,有f(n-1)種跳法,如果第一次跳2級,有f(n - 2)種跳法,即f(n) = f(n-1) + f(n-2)。
即為Fibonacci序列。
復(fù)制代碼 代碼如下:
#include "stdafx.h"
#include <iostream>
using namespace std;
//循環(huán)
int TotalStep(int n)
{
if (n <= 0)
{
return 0;
}
else if (1 == n || 2 == n)
{
return n;
}
int first = 1;
int second = 2;
int total = 0;
for (int i = 3; i <= n; i++)
{
total = first + second;
first = second;
second = total;
}
return total;
}
//遞歸
int RecurTotalStep(int n)
{
if (n <= 0)
{
return 0;
}
else if (n == 1 || n == 2)
{
return n;
}
else
{
return RecurTotalStep(n - 1) + RecurTotalStep(n - 2);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
cout<<TotalStep(20)<<endl;
cout<<RecurTotalStep(20)<<endl;
return 0;
}
運(yùn)行界面如下:

相關(guān)文章
C++中多態(tài)的定義及實(shí)現(xiàn)詳解
這篇文章主要給大家介紹了關(guān)于C++中多態(tài)的定義及實(shí)現(xiàn)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05
適合初學(xué)者的C語言數(shù)據(jù)類型的講解
在 C 語言中,數(shù)據(jù)類型指的是用于聲明不同類型的變量或函數(shù)的一個廣泛的系統(tǒng)。變量的類型決定了變量存儲占用的空間,以及如何解釋存儲的位模式。2022-04-04
基于Qt制作一個定時(shí)關(guān)機(jī)的小程序
這篇文章主要為大家詳細(xì)介紹了如何基于Qt制作一個有趣的定時(shí)關(guān)機(jī)的小程序,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-12-12
C++實(shí)現(xiàn)將數(shù)據(jù)寫入Excel工作表的示例代碼
直觀的界面、出色的計(jì)算功能和圖表工具,使Excel成為最流行的個人計(jì)算機(jī)數(shù)據(jù)處理軟件。在本文中,您將學(xué)習(xí)如何使用?Spire.XLS?for?C++?創(chuàng)建?Excel?文檔,以及如何將數(shù)據(jù)寫入?Excel?工作表2023-03-03

