[Leetcode 70]: Climbing Stairs
阿新 • • 發佈:2018-02-24
div clas lis style tro tair ive script air
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.
Analisis:
這個問題的本質其實就是斐波那契數列, 爬到第n級樓梯的步數,是由f(n-1)與f(n-2) 所控制的。
則: f(1)=1, f(2)=2, f(n)=f(n-1)+f(n-2);
1 int climbStairs(int n) { 2 3 int zr=1; 4 int st=2; 5 int pri=zr, per=st; 6 for(int i=3; i<=n;i++) 7 { 8 if (i & 0x001 == 1) //odd 9 pri=pri+per; 10 else 11 per=pri+per; 12 } 13 if(n & 0x001 ==1)14 return pri; 15 else 16 return per; 17 }
[Leetcode 70]: Climbing Stairs