70. Climbing Stairs
一、问题描述
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.
二、输入输出
三、解题思路
动态规划法
- 用
f(n)
表示爬n级台阶最多有多少种不同的爬法。假设第一步爬了1步,那么f(n) = f(n-1)
,假设第一步爬了2步,那么有f(n) = f(n-2)
。综上,f(n) = f(n-1) + f(n-2) n>=3
f(1) = 1, f(2) = 2
- 当你模拟这个人先走一步的时候,发现这个问题和原来的问题是同型的。那么第一步到底该怎么走哪,这个时候你就可以把所有的情况都分类讨论,然后用这些情况找出你要的那个解
- 动态规划有两种解法
- Recusive and memorize 这种方法把搜索过的解记录下来,递归调用的时候直接查表
- Bottom-Up 这种方法先求小规模问题,依次往上求,最后给出最终结果
class Solution {
public:
int climbStairs(int n) {
if(n == 1) return 1;
if(n == 2) return 2;
int f_n_1 = 2, f_n_2 = 1;
for (int i = 3; i <= n; ++i) {
int f_n = f_n_1 + f_n_2;
f_n_2 = f_n_1;
f_n_1 = f_n;
}
return f_n_1;
}
};