C++:高效解法一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/aaa958099161/article/details/89977139

题目描述 

 一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。

提交代码:


class Solution {
public:
	int jumpFloor(int n) {
		long int f0 = 1;
		long int f1 = 2;
		if (n<1)
		{
			return 0;
		}
			
		if (n == 1)
		{
			return f0;
		}
		if (n == 2)
		{
			return f1;
		}
		long int fn = 0;
		for (int i = 3; i <= n; i++)
		{
			fn = f0 + f1;
			f0 = f1;
			f1 = fn;
		}
		return fn;
	}
};

 测试:

int main()
{
	Solution *s = new Solution();

	long int out =s->jumpFloor(3);
	cout << out << endl;
	system("pause");
	return 0;
}

理解这种解法,看这篇吧,原理一样

https://mp.csdn.net/postedit/89976111 

猜你喜欢

转载自blog.csdn.net/aaa958099161/article/details/89977139