题目描述:
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.
Example 1:
Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps
Example 2:
Input: 3 Output: 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step
思路:
1 public class Solution70 { 2 public int climbStairs(int n){ 3 // //递归的方法,等同于斐波那契数列 4 // if (n == 1) return 1; 5 // if (n == 2) return 2; 6 // return climbStairs(n-1)+climbStairs(n-2); 7 8 //动态规划法1 9 // if (n == 1) return 1; 10 // if (n == 2) return 2; 11 // int f1 = 1; 12 // int f2 = 2; 13 // for(int i = 3; i <= n; i++){ 14 // int tmp = f1 + f2; 15 // f1 = f2; 16 // f2 = tmp; 17 // } 18 // return f2; 19 //动态规划法2 动态规划填表法 20 int[] res = new int[n+1]; 21 res[0] = 1; 22 res[1] = 1; 23 for(int i = 2; i <= n; i++){ 24 res[i] = res[i-1] + res[i-2]; 25 } 26 return res[n]; 27 } 28 public static void main(String[] args) { 29 // TODO Auto-generated method stub 30 Solution70 solution70 = new Solution70(); 31 int n = solution70.climbStairs(1); 32 System.out.println(n); 33 } 34 35 }