Climbing Stairs
Q : 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?
A: 动态规划的题。
记f(n)是爬n steps stair的不同方式。
爬到n层,那么有两种选择:
1. 先爬n-1层,再往上1step
2. 先爬n-2层,再往上2 steps。
那么f(n) = f(n-2) + f(n-1) (Fibonacci数) 注意不要用递归,用DP,o(n)
1 int climbStairs(int n) { 2 // Start typing your C/C++ solution below 3 // DO NOT write int main() function 4 if(n<=0) 5 return 0; 6 7 if(n==1) 8 return 1; 9 10 if(n==2) 11 return 2; 12 13 int a = 1,b = 2,result; 14 15 for(int i=3;i<=n;i++) 16 { 17 result = a+b; 18 a = b; 19 b = result; 20 } 21 22 return result; 23 24 }
浙公网安备 33010602011771号