原题链接:https://leetcode.com/problems/climbing-stairs/description/
实现如下:
/**
* Created by clearbug on 2018/2/26.
*/
public class Solution {
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.climbStairs1(1));
System.out.println(s.climbStairs1(2));
System.out.println(s.climbStairs1(3));
System.out.println(s.climbStairs1(4));
System.out.println(s.climbStairs1(5));
System.out.println(s.climbStairs1(44));
System.out.println(s.climbStairs2(1));
System.out.println(s.climbStairs2(2));
System.out.println(s.climbStairs2(3));
System.out.println(s.climbStairs2(4));
System.out.println(s.climbStairs2(5));
System.out.println(s.climbStairs2(44));
System.out.println(s.climbStairs3(1));
System.out.println(s.climbStairs3(2));
System.out.println(s.climbStairs3(3));
System.out.println(s.climbStairs3(4));
System.out.println(s.climbStairs3(5));
System.out.println(s.climbStairs3(44));
System.out.println(s.climbStairs4(1));
System.out.println(s.climbStairs4(2));
System.out.println(s.climbStairs4(3));
System.out.println(s.climbStairs4(4));
System.out.println(s.climbStairs4(5));
System.out.println(s.climbStairs4(44));
}
/**
* 方法一:分解问题 + 递归
*
* @param n
* @return
*/
public int climbStairs1(int n) {
if (n == 1) {
return 1;
}
if (n == 2) {
return 2;
}
return climbStairs1(n - 1) + climbStairs1(n - 2);
}
/**
* 方法二:倒置方法一,避免深层递归
*
* @param n
* @return
*/
public int climbStairs2(int n) {
if (n == 1) {
return 1;
}
if (n == 2) {
return 2;
}
int n1 = 2, n2 = 1;
for (int i = 3; i < n; i++) {
int curr = n1 + n2;
n2 = n1;
n1 = curr;
}
return n1 + n2;
}
/**
* 官方答案一:使用组合排序,遍历所有走法,暴力却低效
*/
public int climbStairs3(int n) {
return climbStairs3Helper(0, n);
}
private int climbStairs3Helper(int start, int n) {
if (start > n) {
return 0;
}
if (start == n) {
return 1;
}
return climbStairs3Helper(start + 1, n) + climbStairs3Helper(start + 2, n);
}
/**
* 官方答案二:在方法一的基础上加上一个数组来记录已经递归过的答案,避免了重复递归的低效
*/
public int climbStairs4(int n) {
int[] memo = new int[n];
return climbStairs4Helper(0, n, memo);
}
private int climbStairs4Helper(int start, int n, int[] memo) {
if (start > n) {
return 0;
}
if (start == n) {
return 1;
}
if (memo[start] > 0) {
return memo[start];
}
memo[start] = climbStairs4Helper(start + 1, n, memo) + climbStairs4Helper(start + 2, n, memo);
return memo[start];
}
// 官方方法三:动态规划,跟我的方法一和方法二类似
// 官方方法四:斐波那契数列方法,跟我的方法二基本上是一样的
// 官方方法五和六涉及到斐波那契数列的一个公式推导的问题,由于这一块我目前不熟悉,那这两种方法后续再学习吧!
}