Problem:
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.
Explanation:
爬完楼梯需要n步,每次能爬1或2步,有几种爬法。
My Thinking:
My Solution:
Optimum Thinking:
- 暴力解法,每次走1步或2步进行递归,走完的返回1。
- 先递归1后再递归2会出现重复的子树路径计算,使用数组将当前i的路径个数存储以避免重复计算
- 使用动态规划,对于i来说,到它有两种办法,i-1走1步或i-2走两步,对于每个i都是如此,因此有dp[i]=dp[i-1]+dp[i-2],即到i的路径数应该是到i-1的路径数+到i-2的路径数之和。
Optimum Solution:
(1)
class Solution {
public int climbStairs(int n) {
return climbStairs(0,n);
}
public int climbStairs(int i,int n) {
if(i>n)
return 0;
if(i==n)
return 1;
return climbStairs(i+1,n)+climbStairs(i+2,n);
}
}
(2)
class Solution {
public int climbStairs(int n) {
int memo[]=new int[n+1];
return climbStairs(0,n,memo);
}
public int climbStairs(int i,int n,int memo[]) {
if(i>n)
return 0;
if(i==n)
return 1;
if(memo[i]>0)
return memo[i];
memo[i]=climbStairs(i+1,n,memo)+climbStairs(i+2,n,memo);
return memo[i];
}
}
(3)
class Solution {
public int climbStairs(int n) {
if(n==1)
return 1;
int[] dp=new int[n+1];
dp[1]=1;
dp[2]=2;
for(int i=3;i<=n;i++){
dp[i]=dp[i-1]+dp[i-2];
}
return dp[n];
}
}