爬楼梯-算法练习笔记

爬楼梯:

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。

示例 1:

    输入: 2
    输出: 2
    解释: 有两种方法可以爬到楼顶。

示例 2:

    输入: 3
    输出: 3
    解释: 有三种方法可以爬到楼顶。

/**

@author cosefy

@date 2020/6/20
*/
public class ClimbStairs {
static int count = 0;
static int n = 44;
static int[] memo1 = new int[n + 1];

public static void main(String[] args) {
    int res1 = test1(n);
    System.out.println("测试结果: " + res1 + " 调用次数: " + count);
    int res2 = test2(n);
    System.out.println("测试结果: " + res2);
}

//
解法一:递归+记忆存储
public static int test1(int n) {
    count++;
    if (n == 1)
        return 1;
    if (n == 2)
        return 2;
    if (memo1[n] == 0)
        memo1[n] = test1(n - 1) + test1(n - 2);
    return memo1[n];
}
//解法二:动态数组
public static int test2(int n) {
    if (n == 1)
        return 1;
    if (n == 2)
        return 2;
    int[] memo = new int[n + 1];
    memo[1] = 1;
    memo[2] = 2;
    for (int i = 3; i < n + 1; i++) {
        memo[i] = memo[i - 1] + memo[i - 2];
    }
    return memo[n];
}
//解法三:动态数组优化
/*
可以使用三个变量来替代数组。
 */
}
原文地址:https://www.cnblogs.com/cosefy/p/13168417.html