青蛙跳台阶(斐波那契数列应用)

(1)一只青蛙一次可以跳上 1 级台阶,也可以跳上2 级。求该青蛙跳上一个n 级的台阶总共有多少种跳法。

(2)一只青蛙一次可以跳上1级台阶,也可以跳上2 级……它也可以跳上n 级,此时该青蛙跳上一个n级的台阶总共有多少种跳法?


问题1:

题目描述:
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

输入:

输入包括一个整数n(1<=n<=70)。

输出:

输出该青蛙跳上一个n级的台阶总共有多少种跳法。

解:f(n)=f(n-1)+f(n-2)

其矩阵表示方法为:(时间复杂度 O(logn))



#include <iostream>
using namespace std;

class Matrix2By2
{
public:	
	long  x11; 
	long  x12;
	long  x21;
	long  x22;

	Matrix2By2():x11(0),x12(0),x21(0),x22(0){}
	Matrix2By2(long x1,long x2,long x3,long x4):x11(x1),x12(x2),x21(x3),x22(x4){}
	Matrix2By2 & operator *(const Matrix2By2 & temp)
	{
		Matrix2By2 c(x11,x12,x21,x22);
		x11=c.x11*temp.x11+c.x12*temp.x21;
		x12=c.x11*temp.x12+c.x12*temp.x22;
		x21=c.x21*temp.x11+c.x22*temp.x21;
		x22=c.x21*temp.x12+c.x22*temp.x22;
		return *this;
	}
};

Matrix2By2 MatrixPower(int t)
{
	if(t==1)
	{
		return Matrix2By2(1,1,1,0);
	}
	else if(t&1)
	{
		return MatrixPower(t/2)*MatrixPower(t/2)*MatrixPower(1);// (t-1)/2 和 t-1 一样
	}
	else 
	{
		return MatrixPower(t/2)*MatrixPower(t/2);
	}
}

long fab(int n)
{
	if(n==1)
	{
		return 1;
	}
	else if(n==2)
	{
		return 2;
	}
	else
	{
		Matrix2By2 maxtrix = MatrixPower(n);
		return maxtrix.x11;
	}
}

int main()
{
	int n;
	while(cin>>n)
	{
		cout<<fab(n)<<endl;
	}
	
	return 0;
}


问题2:

f(n) = f(n-1) + f(n-2) + ···· f(2) + f(1) 

f(n-1) = f(n-2) + ···· f(2) + f(1)

f(n) - f(n -1)  = f(n-1)

f(n) = 2 f(n-1)

所以:f(n) = 2的n-1次方 *f(1) 

f(1) = 1

最终: f(n) = 2的n-1次方

原文地址:https://www.cnblogs.com/keanuyaoo/p/3348062.html