题目描述:
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
方法一:
1 class Solution { 2 public int climbStairs(int n) { 3 if(n==1||n==2) { 4 return n; 5 } 6 return climbStairs(n-1)+climbStairs(n-2); 7 8 } 9 }
很容易想到上面这种方法,其时间复杂度为O(2^n),提交OJ会超时。
方法2:
如何用递推求出第i阶爬法数量?
1 class Solution { 2 public int climbStairs(int n) { 3 int[] dp=new int[n+3]; 4 dp[1]=1; 5 dp[2]=2; 6 for(int i=3;i<=n;i++) { 7 dp[i]=dp[i-1]+dp[i-2]; 8 } 9 return dp[n]; 10 } 11 }
执行用时在所有Java提交中击败了100.00%的用户!!
动态规划原理:
下一题动态规划经典题目LeetCode198打家劫舍
欢迎评论!!共同进步!!