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步走到台阶n和走2步走到台阶n。如果走一步走到台阶n,那么之前的n-1级台阶有f(n-1)种走法;如果走2步走到台阶n,那么之前的n-2级台阶有f(n-2)种走法,所以一共有f(n-1)+f(n-2)步走法。
代码如下:
1 class Solution { 2 public: 3 int climbStairs(int n) { 4 vector<int> num_method(n+1); 5 num_method[0] = num_method[1] = 1; 6 for(int i = 2;i <= n;i ++) 7 num_method[i] = num_method[i-1]+num_method[i-2]; 8 return num_method[n]; 9 } 10 };
Java代码:不需要数组,只需要保存前面两级台阶的走法数即可。
1 public class Solution { 2 public int climbStairs(int n) { 3 if(n == 1) 4 return 1; 5 if(n == 2) 6 return 2; 7 int first = 1; 8 int second = 2; 9 int answer = 0; 10 for(int i = 3;i <= n;i++) 11 { 12 answer = first + second; 13 first = second; 14 second = answer; 15 } 16 return answer; 17 } 18 }