mirror of
https://github.com/krahets/hello-algo.git
synced 2026-06-28 16:44:22 +00:00
954c45864b
* docs: add Japanese documents (`ja/docs`) * docs: add Japanese documents (`ja/codes`) * docs: add Japanese documents * Remove pythontutor blocks in ja/ * Add an empty at the end of each markdown file. * Add the missing figures (use the English version temporarily). * Add index.md for Japanese version. * Add index.html for Japanese version. * Add missing index.assets * Fix backtracking_algorithm.md for Japanese version. * Add avatar_eltociear.jpg. Fix image links on the Japanese landing page. * Add the Japanese banner. --------- Co-authored-by: krahets <krahets@163.com>
48 lines
1.4 KiB
Java
48 lines
1.4 KiB
Java
/**
|
|
* File: climbing_stairs_dp.java
|
|
* Created Time: 2023-06-30
|
|
* Author: krahets (krahets@163.com)
|
|
*/
|
|
|
|
package chapter_dynamic_programming;
|
|
|
|
public class climbing_stairs_dp {
|
|
/* 階段登り:動的プログラミング */
|
|
public static int climbingStairsDP(int n) {
|
|
if (n == 1 || n == 2)
|
|
return n;
|
|
// DPテーブルを初期化し、部分問題の解を格納するために使用
|
|
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 int climbingStairsDPComp(int n) {
|
|
if (n == 1 || n == 2)
|
|
return n;
|
|
int a = 1, b = 2;
|
|
for (int i = 3; i <= n; i++) {
|
|
int tmp = b;
|
|
b = a + b;
|
|
a = tmp;
|
|
}
|
|
return b;
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
int n = 9;
|
|
|
|
int res = climbingStairsDP(n);
|
|
System.out.println(String.format("%d段の階段を登る解は%d通りです", n, res));
|
|
|
|
res = climbingStairsDPComp(n);
|
|
System.out.println(String.format("%d段の階段を登る解は%d通りです", n, res));
|
|
}
|
|
} |