题目描述:假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
获得更多?算法思路:代码文档,算法解析的私得。
完整代码
/**
* 2 * @Author: LJJ
* 3 * @Date: 2023/7/26 13:31
* 4
*/
public class ClimbStairs {
public static int climbStairs(int n) {
if (n <= 2) {
return n;
}
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];
}
public static void printClimbStairs(int n) {
System.out.println("Different ways to climb " + n + " stairs:");
printClimbStairsHelper(n, "");
}
public static void printClimbStairsHelper(int n, String path) {
if (n == 0) {
System.out.println(path);
return;
}
if (n >= 1) {
printClimbStairsHelper(n - 1, path + "1 -> ");
}
if (n >= 2) {
printClimbStairsHelper(n - 2, path + "2 -> ");
}
}
public static void main(String[] args) {
int n = 5;
int ways = climbStairs(n);
System.out.println("Number of ways to climb " + n + " stairs: " + ways);
printClimbStairs(n);
}
}