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?
1 自己的代码:运行并不成功,相对于对每个小于n的元素进行了两倍的操作,超时。
2 动态规划代码
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
1 自己的代码:运行并不成功,相对于对每个小于n的元素进行了两倍的操作,超时。
package leetcode;
public class ClimbingStairs {
public int climbStairs(int n) {
if(n == 1) return 1;
if(n == 2) return 2;
int sum = 0;
if(n > 2){
sum += climbStairs(n - 1) + climbStairs(n - 2);
}
return sum;
}
}
2 动态规划代码
package leetcode;
public class ClimbingStairs {
public int climbStairs(int n) {
if(n == 1) return 1;
if(n == 2) return 2;
int returns = 0;
if(n > 2){
int[] sum = new int[n+1];
sum[1] = 1;
sum[2] = 2;
for(int i = 3; i < n+1; i++)
sum[i] = sum[i-1] + sum[i-2];
returns = sum[n];
}
return returns;
}
}