Leetcode 70. Climbing Stairs

70. Climbing Stairs

  • Total Accepted: 120408
  • Total Submissions: 321825
  • Difficulty: 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?

 

思路:DP,其实就是斐波那契数列(Fibonacci sequence)。

 

代码:

 1 class Solution {
 2 public:
 3     int climbStairs(int n) {
 4         if(n<1) return 0;
 5         if(n<=2) return n;
 6         int one_step_before=2;
 7         int two_steps_before=1;
 8         int sum_steps;
 9         for(int i=3;i<=n;i++){
10             sum_steps=one_step_before+two_steps_before;
11             two_steps_before=one_step_before;
12             one_step_before=sum_steps;
13         }
14         return sum_steps;
15     }
16 };

 

posted @ 2016-07-29 15:50  Deribs4  阅读(279)  评论(0)    收藏  举报