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?

这道题目其实就是斐波那契数列问题,题目比较简单,我们很容易就能列出dp方程

dp[n] = dp[n - 1] + dp[n - 2]

初始条件dp[1] = 1, dp[2] = 2。

代码如下:

  1. class Solution {
  2. public:
  3. int climbStairs(int n) {
  4. int f1 = 2;
  5. int f2 = 1;
  6. if(n == 1) {
  7. return f2;
  8. } else if(n == 2) {
  9. return f1;
  10. }
  11. int fn;
  12. for(int i = 3; i <= n; i++) {
  13. fn = f1 + f2;
  14. f2 = f1;
  15. f1 = fn;
  16. }
  17. return fn;
  18. }
  19. };