题目要求:
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?
Subscribe to see which companies asked this question
Show Tags
–
(1)使用递归的方式进行处理,但是随着递归深度的增加,时间复杂度以及内存的开销越来越大,最终显示时间超时.
思路: 最后的步数只是会与最后是 2步还是1步走完有关.
f(n) = f(n-1) + f(n-2);
public class solution {
public int climbStairs(int n) {
//使用递归的方式进行处理
if(n == 1) return 1;
if(n == 2) return 2;
return climbStairs(n - 1) + climbStairs(n - 2);
}
}
解法2:使用斐波那契数列进行求解
public class solution_fix {
//使用斐波那契数列
public int climbStairs(int n) {
int[] arr = new int[n + 1];
arr[0] = 1;
arr[1] = 1;
for(int i = 0; i < n - 1; i++) {
arr[i + 2] = arr[i] + arr[i + 1];
}
return arr[n];
}
}