Climbing Stairs 爬樓梯問題,每次可以走1或2步,爬上n層樓梯總方法 (變相fibonacci)

範長法@三月軟體發表於2014-10-29

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?

當n=1時,有1種方法,即直接走1步

當n=2時,有2方法:連續走2步,或直接走兩步

對於n,設f(n)為總方法,則 f(n) = f(n-1)+f(n-2)  

ps:f(n-1)即第一次走一步的走法,

    f(n-2)即第一次走兩步的走法

歸回fibnacci問題解法:

 1 class Solution {
 2 public:
 3     int climbStairs(int n) {
 4         if(n < 0)
 5             return -1;
 6         int res[] = {0,1};
 7         if(n<2)
 8             return res[n];
 9             
10         int fib1 = 0;
11         int fib2 = 1;
12         
13         int result = 1;
14         
15         for(int i = 1 ; i <= n ; i++){
16             result = fib1 + fib2;
17             fib1 = fib2;
18             fib2 = result;
19         }
20         
21         return result;
22     }
23 };

 

相關文章