c語言 跳臺階問題的解決方法
更新時間:2013年05月24日 09:29:20 作者:
本篇文章是對c語言中跳臺階問題的解決方法進行了詳細的分析介紹,需要的朋友參考下
題目:一個臺階總共有n級,如果一次可以跳1級,也可以跳2級。求總共有多少種跳法,并分析算法的時間復雜度。
答:用一個函數(shù)f(n)來表示n級臺階總的跳法。
1、只有1個臺階,則f(1) = 1;
2、有2個臺階,則f(2) = 2;
3、當有n個臺階時,如果第一次跳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;
}
運行界面如下:
答:用一個函數(shù)f(n)來表示n級臺階總的跳法。
1、只有1個臺階,則f(1) = 1;
2、有2個臺階,則f(2) = 2;
3、當有n個臺階時,如果第一次跳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;
}
運行界面如下:

相關文章
C++實現(xiàn)將數(shù)據(jù)寫入Excel工作表的示例代碼
直觀的界面、出色的計算功能和圖表工具,使Excel成為最流行的個人計算機數(shù)據(jù)處理軟件。在本文中,您將學習如何使用?Spire.XLS?for?C++?創(chuàng)建?Excel?文檔,以及如何將數(shù)據(jù)寫入?Excel?工作表2023-03-03

