70. Climbing Stairs
problem description
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.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 stepsExample 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 stepalgorithm thought
说是爬楼梯,其实就是斐波拉契数列。当前值等于前两个的值相加。可以用动态规划解决,用一个一维数组保存所有结果。也可以直接用两个变量保存之前的两个数的值,而不保存所有的结果。
code
algorithm analysis
利用动态规划来解决斐波拉契数列问题,时间复杂度O(n),第二种方法相对于第一种方法减少了线性数组的开销,空间复杂度从O(n)减到了O(1)。
Last updated