【LeetCode】18.Climbing Stairs

题目描述(Easy)

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer.

题目链接

https://leetcode.com/problems/climbing-stairs/description/

Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step.

算法分析

动态规划,斐波那契数列问题,f(n) = f(n - 1) + f(n - 2)。

提交代码:

class Solution {
public:
	int climbStairs(int n) {
		if (n == 1) return 1;
		if (n == 2) return 2;
		int prev = 2, pprev = 1;
		int result = 0;

		for (int i = 3; i <= n; ++i)
		{
			result = prev + pprev;
			pprev = prev;
			prev = result;
		}

		return result;
	}
};

测试代码:

// ====================测试代码====================
void Test(const char* testName, int n, int expected)
{
	if (testName != nullptr)
		printf("%s begins: \n", testName);

	Solution s;
	int result = s.climbStairs(n);

	if (result == expected)
		printf("passed\n");
	else
		printf("failed\n");

}

int main(int argc, char* argv[])
{
	Test("Test1", 2, 2);
	Test("Test2", 3, 3);
	Test("Test3", 1, 1);
	Test("Test4", 4, 5);

	return 0;
}

猜你喜欢

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