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