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:
1 | Input: 2 |
Example 2:
1 | Input: 3 |
解法
最开始的想法是DFS暴力搜索所有可能的情况,毫无疑问,超时了0.0
1 | class Solution { |
仔细一想,貌似可以采用动态规划的思想,因为走到台阶n有两种可能的走法,一种是从n-1迈一步上来,一种是从n-2迈2步上来,于是有dp[n] = dp[n-1] + dp[n-2]。额,这不就是斐波那契数列吗0.0
1 | class Solution { |
很遗憾,还是超时了0.0。问题在于重复计算。因此,采用记忆化避免重复计算,最终成功AC~(^-^)
具体代码如下:
1 | class Solution { |