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?ios
分析
設 f(n) 表示爬 n 階樓梯的不一樣方法數,爲了爬到第 n 階樓梯,有兩個選擇:
• 從第 n − 1 階前進 1 步;
• 從第 n − 1 階前進 2 步;
所以,有 f(n) = f(n − 1) + f(n − 2)。
這是一個斐波那契數列。數組
兩種方法,一是迭代,二是遞歸spa
#include <iostream> using namespace std; int climbStairs(int n) { int prev = 0; int cur = 1; for(int i = 1; i <= n ; ++i) { int tmp = cur; cur = prev + cur; prev = tmp; } return cur; } int climbStairs2(int n) { if (n<=0) { return 0; } if (n==1) { return 1; } if (n==2) { return 2; } if (n>2) { int ans=climbStairs2(n-1)+climbStairs2(n-2); return ans; } } int main() { int stairs=4; int ans=climbStairs(stairs); cout<<"ans1 is "<<ans<<endl; int ans2=climbStairs2(stairs); cout<<"ans2 is "<<ans2<<endl; return 0; }