【剑指】10(2).跳台阶

题目描述

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

算法分析

  • 跳第n级台阶,可以先跳1级台阶,再跳n-1阶台阶,也可以先跳2级台阶,再跳n-2阶台阶,即f(n)=f(n-1)+f(n-2)

提交代码:

class Solution {
public:
	int jumpFloor(int number) {
		if (number < 1)
			return 0;
		if (number == 1)
			return 1;
		if (number == 2)
			return 2;

		int pre = 1;
		int now = 2;
		for (int i = 3; i <= number; ++i)
		{
			int temp = pre + now;
			pre = now;
			now = temp;
		}
		return now;
	}
};

测试代码:

// ====================测试代码====================
void Test(int n, int expected)
{
	Solution s;
	if (s.jumpFloor(n) == expected)
		printf("Test for %d in solution1 passed.\n", n);
	else
		printf("Test for %d in solution1 failed.\n", n);
}

int main(int argc, char* argv[])
{
	Test(0, 0);
	Test(1, 1);
	Test(2, 2);
	Test(3, 3);
	Test(4, 5);
	Test(5, 8);
	Test(6, 13);
	Test(7, 21);
	Test(8, 34);
	Test(9, 55);
	Test(10, 89);

	return 0;
}


猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/80385485