mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-10 16:00:36 +08:00
Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
This commit is contained in:
@@ -11,26 +11,26 @@ import java.util.*;
|
||||
public class climbing_stairs_backtrack {
|
||||
/* Backtracking */
|
||||
public static void backtrack(List<Integer> choices, int state, int n, List<Integer> res) {
|
||||
// When climbing to the n-th stair, add 1 to the solution count
|
||||
// When step n is reached, increase the number of ways by 1
|
||||
if (state == n)
|
||||
res.set(0, res.get(0) + 1);
|
||||
// Traverse all choices
|
||||
// Iterate over all choices
|
||||
for (Integer choice : choices) {
|
||||
// Pruning: not allowed to go beyond the n-th stair
|
||||
// Prune: do not go beyond step n
|
||||
if (state + choice > n)
|
||||
continue;
|
||||
// Attempt: make choice, update state
|
||||
// Try: make a choice and update the state
|
||||
backtrack(choices, state + choice, n, res);
|
||||
// Backtrack
|
||||
}
|
||||
}
|
||||
|
||||
/* Climbing stairs: Backtracking */
|
||||
/* Climbing stairs: backtracking */
|
||||
public static int climbingStairsBacktrack(int n) {
|
||||
List<Integer> choices = Arrays.asList(1, 2); // Can choose to climb up 1 or 2 stairs
|
||||
int state = 0; // Start climbing from the 0-th stair
|
||||
List<Integer> choices = Arrays.asList(1, 2); // Choose to climb 1 or 2 steps
|
||||
int state = 0; // Start climbing from step 0
|
||||
List<Integer> res = new ArrayList<>();
|
||||
res.add(0); // Use res[0] to record the solution count
|
||||
res.add(0); // Use res[0] to record the number of ways
|
||||
backtrack(choices, state, n, res);
|
||||
return res.get(0);
|
||||
}
|
||||
@@ -39,6 +39,6 @@ public class climbing_stairs_backtrack {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsBacktrack(n);
|
||||
System.out.println(String.format("Climbing %d stairs has %d solutions", n, res));
|
||||
System.out.println(String.format("Number of ways to climb %d stairs: %d", n, res));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,19 +7,19 @@
|
||||
package chapter_dynamic_programming;
|
||||
|
||||
public class climbing_stairs_constraint_dp {
|
||||
/* Climbing stairs with constraint: Dynamic programming */
|
||||
/* Climbing stairs with constraints: dynamic programming */
|
||||
static int climbingStairsConstraintDP(int n) {
|
||||
if (n == 1 || n == 2) {
|
||||
return 1;
|
||||
}
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
// Initialize the dp table to store subproblem solutions
|
||||
int[][] dp = new int[n + 1][3];
|
||||
// Initial state: preset the solution to the smallest subproblem
|
||||
// Initial states: set the solutions to the smallest subproblems
|
||||
dp[1][1] = 1;
|
||||
dp[1][2] = 0;
|
||||
dp[2][1] = 0;
|
||||
dp[2][2] = 1;
|
||||
// State transition: gradually solve larger subproblems from smaller ones
|
||||
// State transitions: solve progressively larger subproblems using smaller ones
|
||||
for (int i = 3; i <= n; i++) {
|
||||
dp[i][1] = dp[i - 1][2];
|
||||
dp[i][2] = dp[i - 2][1] + dp[i - 2][2];
|
||||
@@ -31,6 +31,6 @@ public class climbing_stairs_constraint_dp {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsConstraintDP(n);
|
||||
System.out.println(String.format("Climbing %d stairs has %d solutions", n, res));
|
||||
System.out.println(String.format("Number of ways to climb %d stairs: %d", n, res));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ package chapter_dynamic_programming;
|
||||
public class climbing_stairs_dfs {
|
||||
/* Search */
|
||||
public static int dfs(int i) {
|
||||
// Known dp[1] and dp[2], return them
|
||||
// The values of dp[1] and dp[2] are known; return them
|
||||
if (i == 1 || i == 2)
|
||||
return i;
|
||||
// dp[i] = dp[i-1] + dp[i-2]
|
||||
@@ -17,7 +17,7 @@ public class climbing_stairs_dfs {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Climbing stairs: Search */
|
||||
/* Climbing stairs: search */
|
||||
public static int climbingStairsDFS(int n) {
|
||||
return dfs(n);
|
||||
}
|
||||
@@ -26,6 +26,6 @@ public class climbing_stairs_dfs {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsDFS(n);
|
||||
System.out.println(String.format("Climbing %d stairs has %d solutions", n, res));
|
||||
System.out.println(String.format("Number of ways to climb %d stairs: %d", n, res));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,12 +9,12 @@ package chapter_dynamic_programming;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class climbing_stairs_dfs_mem {
|
||||
/* Memoization search */
|
||||
/* Memoized search */
|
||||
public static int dfs(int i, int[] mem) {
|
||||
// Known dp[1] and dp[2], return them
|
||||
// The values of dp[1] and dp[2] are known; return them
|
||||
if (i == 1 || i == 2)
|
||||
return i;
|
||||
// If record dp[i] exists, return it directly
|
||||
// If dp[i] has been recorded, return it directly
|
||||
if (mem[i] != -1)
|
||||
return mem[i];
|
||||
// dp[i] = dp[i-1] + dp[i-2]
|
||||
@@ -24,9 +24,9 @@ public class climbing_stairs_dfs_mem {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Climbing stairs: Memoization search */
|
||||
/* Climbing stairs: memoized search */
|
||||
public static int climbingStairsDFSMem(int n) {
|
||||
// mem[i] records the total number of solutions to climb to the i-th stair, -1 means no record
|
||||
// mem[i] stores the number of ways to reach step i; -1 means no result has been recorded
|
||||
int[] mem = new int[n + 1];
|
||||
Arrays.fill(mem, -1);
|
||||
return dfs(n, mem);
|
||||
@@ -36,6 +36,6 @@ public class climbing_stairs_dfs_mem {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsDFSMem(n);
|
||||
System.out.println(String.format("Climbing %d stairs has %d solutions", n, res));
|
||||
System.out.println(String.format("Number of ways to climb %d stairs: %d", n, res));
|
||||
}
|
||||
}
|
||||
@@ -7,23 +7,23 @@
|
||||
package chapter_dynamic_programming;
|
||||
|
||||
public class climbing_stairs_dp {
|
||||
/* Climbing stairs: Dynamic programming */
|
||||
/* Climbing stairs: dynamic programming */
|
||||
public static int climbingStairsDP(int n) {
|
||||
if (n == 1 || n == 2)
|
||||
return n;
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
// Initialize the dp table to store subproblem solutions
|
||||
int[] dp = new int[n + 1];
|
||||
// Initial state: preset the solution to the smallest subproblem
|
||||
// Initial states: set the solutions to the smallest subproblems
|
||||
dp[1] = 1;
|
||||
dp[2] = 2;
|
||||
// State transition: gradually solve larger subproblems from smaller ones
|
||||
// State transitions: solve progressively larger subproblems using smaller ones
|
||||
for (int i = 3; i <= n; i++) {
|
||||
dp[i] = dp[i - 1] + dp[i - 2];
|
||||
}
|
||||
return dp[n];
|
||||
}
|
||||
|
||||
/* Climbing stairs: Space-optimized dynamic programming */
|
||||
/* Climbing stairs: space-optimized dynamic programming */
|
||||
public static int climbingStairsDPComp(int n) {
|
||||
if (n == 1 || n == 2)
|
||||
return n;
|
||||
@@ -40,9 +40,9 @@ public class climbing_stairs_dp {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsDP(n);
|
||||
System.out.println(String.format("Climbing %d stairs has %d solutions", n, res));
|
||||
System.out.println(String.format("Number of ways to climb %d stairs: %d", n, res));
|
||||
|
||||
res = climbingStairsDPComp(n);
|
||||
System.out.println(String.format("Climbing %d stairs has %d solutions", n, res));
|
||||
System.out.println(String.format("Number of ways to climb %d stairs: %d", n, res));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,24 +9,24 @@ package chapter_dynamic_programming;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class coin_change {
|
||||
/* Coin change: Dynamic programming */
|
||||
/* Coin change: dynamic programming */
|
||||
static int coinChangeDP(int[] coins, int amt) {
|
||||
int n = coins.length;
|
||||
int MAX = amt + 1;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
int[][] dp = new int[n + 1][amt + 1];
|
||||
// State transition: first row and first column
|
||||
// State transitions: first row and first column
|
||||
for (int a = 1; a <= amt; a++) {
|
||||
dp[0][a] = MAX;
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
// State transitions: remaining rows and columns
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// If exceeds target amount, don't select coin i
|
||||
// If the coin exceeds the target amount, do not choose coin i
|
||||
dp[i][a] = dp[i - 1][a];
|
||||
} else {
|
||||
// The smaller value between not selecting and selecting coin i
|
||||
// Take the smaller result of not choosing and choosing coin i
|
||||
dp[i][a] = Math.min(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1);
|
||||
}
|
||||
}
|
||||
@@ -34,22 +34,22 @@ public class coin_change {
|
||||
return dp[n][amt] != MAX ? dp[n][amt] : -1;
|
||||
}
|
||||
|
||||
/* Coin change: Space-optimized dynamic programming */
|
||||
/* Coin change: space-optimized dynamic programming */
|
||||
static int coinChangeDPComp(int[] coins, int amt) {
|
||||
int n = coins.length;
|
||||
int MAX = amt + 1;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
int[] dp = new int[amt + 1];
|
||||
Arrays.fill(dp, MAX);
|
||||
dp[0] = 0;
|
||||
// State transition
|
||||
// State transitions
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// If exceeds target amount, don't select coin i
|
||||
// If the coin exceeds the target amount, do not choose coin i
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// The smaller value between not selecting and selecting coin i
|
||||
// Take the smaller result of not choosing and choosing coin i
|
||||
dp[a] = Math.min(dp[a], dp[a - coins[i - 1]] + 1);
|
||||
}
|
||||
}
|
||||
@@ -63,10 +63,10 @@ public class coin_change {
|
||||
|
||||
// Dynamic programming
|
||||
int res = coinChangeDP(coins, amt);
|
||||
System.out.println("Minimum number of coins needed to make target amount is " + res);
|
||||
System.out.println("Minimum number of coins needed to make the target amount: " + res);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = coinChangeDPComp(coins, amt);
|
||||
System.out.println("Minimum number of coins needed to make target amount is " + res);
|
||||
System.out.println("Minimum number of coins needed to make the target amount: " + res);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,23 +7,23 @@
|
||||
package chapter_dynamic_programming;
|
||||
|
||||
public class coin_change_ii {
|
||||
/* Coin change II: Dynamic programming */
|
||||
/* Coin change II: dynamic programming */
|
||||
static int coinChangeIIDP(int[] coins, int amt) {
|
||||
int n = coins.length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
int[][] dp = new int[n + 1][amt + 1];
|
||||
// Initialize first column
|
||||
// Initialize the first column
|
||||
for (int i = 0; i <= n; i++) {
|
||||
dp[i][0] = 1;
|
||||
}
|
||||
// State transition
|
||||
// State transitions
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// If exceeds target amount, don't select coin i
|
||||
// If the coin exceeds the target amount, do not choose coin i
|
||||
dp[i][a] = dp[i - 1][a];
|
||||
} else {
|
||||
// Sum of the two options: not selecting and selecting coin i
|
||||
// Add the numbers of ways without and with coin i
|
||||
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]];
|
||||
}
|
||||
}
|
||||
@@ -31,20 +31,20 @@ public class coin_change_ii {
|
||||
return dp[n][amt];
|
||||
}
|
||||
|
||||
/* Coin change II: Space-optimized dynamic programming */
|
||||
/* Coin change II: space-optimized dynamic programming */
|
||||
static int coinChangeIIDPComp(int[] coins, int amt) {
|
||||
int n = coins.length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
int[] dp = new int[amt + 1];
|
||||
dp[0] = 1;
|
||||
// State transition
|
||||
// State transitions
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// If exceeds target amount, don't select coin i
|
||||
// If the coin exceeds the target amount, do not choose coin i
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// Sum of the two options: not selecting and selecting coin i
|
||||
// Add the numbers of ways without and with coin i
|
||||
dp[a] = dp[a] + dp[a - coins[i - 1]];
|
||||
}
|
||||
}
|
||||
@@ -58,10 +58,10 @@ public class coin_change_ii {
|
||||
|
||||
// Dynamic programming
|
||||
int res = coinChangeIIDP(coins, amt);
|
||||
System.out.println("Number of coin combinations to make target amount is " + res);
|
||||
System.out.println("Number of coin combinations that make the target amount: " + res);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = coinChangeIIDPComp(coins, amt);
|
||||
System.out.println("Number of coin combinations to make target amount is " + res);
|
||||
System.out.println("Number of coin combinations that make the target amount: " + res);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,73 +9,73 @@ package chapter_dynamic_programming;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class edit_distance {
|
||||
/* Edit distance: Brute-force search */
|
||||
/* Edit distance: brute-force search */
|
||||
static int editDistanceDFS(String s, String t, int i, int j) {
|
||||
// If both s and t are empty, return 0
|
||||
// If the current prefixes of s and t are both empty, return 0
|
||||
if (i == 0 && j == 0)
|
||||
return 0;
|
||||
// If s is empty, return length of t
|
||||
// If the current prefix of s is empty, return j, the length of the current prefix of t
|
||||
if (i == 0)
|
||||
return j;
|
||||
// If t is empty, return length of s
|
||||
// If the current prefix of t is empty, return i, the length of the current prefix of s
|
||||
if (j == 0)
|
||||
return i;
|
||||
// If two characters are equal, skip both characters
|
||||
// If the two characters are equal, skip both of them
|
||||
if (s.charAt(i - 1) == t.charAt(j - 1))
|
||||
return editDistanceDFS(s, t, i - 1, j - 1);
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
|
||||
int insert = editDistanceDFS(s, t, i, j - 1);
|
||||
int delete = editDistanceDFS(s, t, i - 1, j);
|
||||
int replace = editDistanceDFS(s, t, i - 1, j - 1);
|
||||
// Return minimum edit steps
|
||||
// Return the minimum number of edits
|
||||
return Math.min(Math.min(insert, delete), replace) + 1;
|
||||
}
|
||||
|
||||
/* Edit distance: Memoization search */
|
||||
/* Edit distance: memoized search */
|
||||
static int editDistanceDFSMem(String s, String t, int[][] mem, int i, int j) {
|
||||
// If both s and t are empty, return 0
|
||||
// If the current prefixes of s and t are both empty, return 0
|
||||
if (i == 0 && j == 0)
|
||||
return 0;
|
||||
// If s is empty, return length of t
|
||||
// If the current prefix of s is empty, return j, the length of the current prefix of t
|
||||
if (i == 0)
|
||||
return j;
|
||||
// If t is empty, return length of s
|
||||
// If the current prefix of t is empty, return i, the length of the current prefix of s
|
||||
if (j == 0)
|
||||
return i;
|
||||
// If there's a record, return it directly
|
||||
// If a result has already been recorded, return it directly
|
||||
if (mem[i][j] != -1)
|
||||
return mem[i][j];
|
||||
// If two characters are equal, skip both characters
|
||||
// If the two characters are equal, skip both of them
|
||||
if (s.charAt(i - 1) == t.charAt(j - 1))
|
||||
return editDistanceDFSMem(s, t, mem, i - 1, j - 1);
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
|
||||
int insert = editDistanceDFSMem(s, t, mem, i, j - 1);
|
||||
int delete = editDistanceDFSMem(s, t, mem, i - 1, j);
|
||||
int replace = editDistanceDFSMem(s, t, mem, i - 1, j - 1);
|
||||
// Record and return minimum edit steps
|
||||
// Record and return the minimum number of edits
|
||||
mem[i][j] = Math.min(Math.min(insert, delete), replace) + 1;
|
||||
return mem[i][j];
|
||||
}
|
||||
|
||||
/* Edit distance: Dynamic programming */
|
||||
/* Edit distance: dynamic programming */
|
||||
static int editDistanceDP(String s, String t) {
|
||||
int n = s.length(), m = t.length();
|
||||
int[][] dp = new int[n + 1][m + 1];
|
||||
// State transition: first row and first column
|
||||
// State transitions: first row and first column
|
||||
for (int i = 1; i <= n; i++) {
|
||||
dp[i][0] = i;
|
||||
}
|
||||
for (int j = 1; j <= m; j++) {
|
||||
dp[0][j] = j;
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
// State transitions: remaining rows and columns
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int j = 1; j <= m; j++) {
|
||||
if (s.charAt(i - 1) == t.charAt(j - 1)) {
|
||||
// If two characters are equal, skip both characters
|
||||
// If the two characters are equal, skip both of them
|
||||
dp[i][j] = dp[i - 1][j - 1];
|
||||
} else {
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
|
||||
dp[i][j] = Math.min(Math.min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
|
||||
}
|
||||
}
|
||||
@@ -83,30 +83,30 @@ public class edit_distance {
|
||||
return dp[n][m];
|
||||
}
|
||||
|
||||
/* Edit distance: Space-optimized dynamic programming */
|
||||
/* Edit distance: space-optimized dynamic programming */
|
||||
static int editDistanceDPComp(String s, String t) {
|
||||
int n = s.length(), m = t.length();
|
||||
int[] dp = new int[m + 1];
|
||||
// State transition: first row
|
||||
// State transitions: first row
|
||||
for (int j = 1; j <= m; j++) {
|
||||
dp[j] = j;
|
||||
}
|
||||
// State transition: rest of the rows
|
||||
// State transitions: remaining rows
|
||||
for (int i = 1; i <= n; i++) {
|
||||
// State transition: first column
|
||||
// State transitions: first column
|
||||
int leftup = dp[0]; // Temporarily store dp[i-1, j-1]
|
||||
dp[0] = i;
|
||||
// State transition: rest of the columns
|
||||
// State transitions: remaining columns
|
||||
for (int j = 1; j <= m; j++) {
|
||||
int temp = dp[j];
|
||||
if (s.charAt(i - 1) == t.charAt(j - 1)) {
|
||||
// If two characters are equal, skip both characters
|
||||
// If the two characters are equal, skip both of them
|
||||
dp[j] = leftup;
|
||||
} else {
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
|
||||
dp[j] = Math.min(Math.min(dp[j - 1], dp[j]), leftup) + 1;
|
||||
}
|
||||
leftup = temp; // Update for next round's dp[i-1, j-1]
|
||||
leftup = temp; // Update to dp[i-1, j-1] for the next iteration
|
||||
}
|
||||
}
|
||||
return dp[m];
|
||||
@@ -119,21 +119,21 @@ public class edit_distance {
|
||||
|
||||
// Brute-force search
|
||||
int res = editDistanceDFS(s, t, n, m);
|
||||
System.out.println("Changing " + s + " to " + t + " requires a minimum of " + res + " edits");
|
||||
System.out.println("Changing " + s + " to " + t + " requires at least " + res + " edits");
|
||||
|
||||
// Memoization search
|
||||
// Memoized search
|
||||
int[][] mem = new int[n + 1][m + 1];
|
||||
for (int[] row : mem)
|
||||
Arrays.fill(row, -1);
|
||||
res = editDistanceDFSMem(s, t, mem, n, m);
|
||||
System.out.println("Changing " + s + " to " + t + " requires a minimum of " + res + " edits");
|
||||
System.out.println("Changing " + s + " to " + t + " requires at least " + res + " edits");
|
||||
|
||||
// Dynamic programming
|
||||
res = editDistanceDP(s, t);
|
||||
System.out.println("Changing " + s + " to " + t + " requires a minimum of " + res + " edits");
|
||||
System.out.println("Changing " + s + " to " + t + " requires at least " + res + " edits");
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = editDistanceDPComp(s, t);
|
||||
System.out.println("Changing " + s + " to " + t + " requires a minimum of " + res + " edits");
|
||||
System.out.println("Changing " + s + " to " + t + " requires at least " + res + " edits");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,58 +10,58 @@ import java.util.Arrays;
|
||||
|
||||
public class knapsack {
|
||||
|
||||
/* 0-1 knapsack: Brute-force search */
|
||||
/* 0-1 knapsack: brute-force search */
|
||||
static int knapsackDFS(int[] wgt, int[] val, int i, int c) {
|
||||
// If all items have been selected or knapsack has no remaining capacity, return value 0
|
||||
// If all items have been considered or no capacity remains, return value 0
|
||||
if (i == 0 || c == 0) {
|
||||
return 0;
|
||||
}
|
||||
// If exceeds knapsack capacity, can only choose not to put it in
|
||||
// If the item exceeds the remaining capacity, it must be excluded
|
||||
if (wgt[i - 1] > c) {
|
||||
return knapsackDFS(wgt, val, i - 1, c);
|
||||
}
|
||||
// Calculate the maximum value of not putting in and putting in item i
|
||||
// Calculate the maximum values obtained by excluding and including item i
|
||||
int no = knapsackDFS(wgt, val, i - 1, c);
|
||||
int yes = knapsackDFS(wgt, val, i - 1, c - wgt[i - 1]) + val[i - 1];
|
||||
// Return the larger value of the two options
|
||||
// Return the larger value from the two choices
|
||||
return Math.max(no, yes);
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Memoization search */
|
||||
/* 0-1 knapsack: memoized search */
|
||||
static int knapsackDFSMem(int[] wgt, int[] val, int[][] mem, int i, int c) {
|
||||
// If all items have been selected or knapsack has no remaining capacity, return value 0
|
||||
// If all items have been considered or no capacity remains, return value 0
|
||||
if (i == 0 || c == 0) {
|
||||
return 0;
|
||||
}
|
||||
// If there's a record, return it directly
|
||||
// If a result has already been recorded, return it directly
|
||||
if (mem[i][c] != -1) {
|
||||
return mem[i][c];
|
||||
}
|
||||
// If exceeds knapsack capacity, can only choose not to put it in
|
||||
// If the item exceeds the remaining capacity, it must be excluded
|
||||
if (wgt[i - 1] > c) {
|
||||
return knapsackDFSMem(wgt, val, mem, i - 1, c);
|
||||
}
|
||||
// Calculate the maximum value of not putting in and putting in item i
|
||||
// Calculate the maximum values obtained by excluding and including item i
|
||||
int no = knapsackDFSMem(wgt, val, mem, i - 1, c);
|
||||
int yes = knapsackDFSMem(wgt, val, mem, i - 1, c - wgt[i - 1]) + val[i - 1];
|
||||
// Record and return the larger value of the two options
|
||||
// Record and return the larger value from the two choices
|
||||
mem[i][c] = Math.max(no, yes);
|
||||
return mem[i][c];
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Dynamic programming */
|
||||
/* 0-1 knapsack: dynamic programming */
|
||||
static int knapsackDP(int[] wgt, int[] val, int cap) {
|
||||
int n = wgt.length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
int[][] dp = new int[n + 1][cap + 1];
|
||||
// State transition
|
||||
// State transitions
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int c = 1; c <= cap; c++) {
|
||||
if (wgt[i - 1] > c) {
|
||||
// If exceeds knapsack capacity, don't select item i
|
||||
// If item i exceeds the remaining capacity, do not choose it
|
||||
dp[i][c] = dp[i - 1][c];
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
dp[i][c] = Math.max(dp[i - 1][c], dp[i - 1][c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
@@ -69,17 +69,17 @@ public class knapsack {
|
||||
return dp[n][cap];
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Space-optimized dynamic programming */
|
||||
/* 0-1 knapsack: space-optimized dynamic programming */
|
||||
static int knapsackDPComp(int[] wgt, int[] val, int cap) {
|
||||
int n = wgt.length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
int[] dp = new int[cap + 1];
|
||||
// State transition
|
||||
// State transitions
|
||||
for (int i = 1; i <= n; i++) {
|
||||
// Traverse in reverse order
|
||||
// Traverse in decreasing order
|
||||
for (int c = cap; c >= 1; c--) {
|
||||
if (wgt[i - 1] <= c) {
|
||||
// The larger value between not selecting and selecting item i
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
dp[c] = Math.max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
@@ -95,22 +95,22 @@ public class knapsack {
|
||||
|
||||
// Brute-force search
|
||||
int res = knapsackDFS(wgt, val, n, cap);
|
||||
System.out.println("Maximum item value not exceeding knapsack capacity is " + res);
|
||||
System.out.println("Maximum total item value within the knapsack capacity: " + res);
|
||||
|
||||
// Memoization search
|
||||
// Memoized search
|
||||
int[][] mem = new int[n + 1][cap + 1];
|
||||
for (int[] row : mem) {
|
||||
Arrays.fill(row, -1);
|
||||
}
|
||||
res = knapsackDFSMem(wgt, val, mem, n, cap);
|
||||
System.out.println("Maximum item value not exceeding knapsack capacity is " + res);
|
||||
System.out.println("Maximum total item value within the knapsack capacity: " + res);
|
||||
|
||||
// Dynamic programming
|
||||
res = knapsackDP(wgt, val, cap);
|
||||
System.out.println("Maximum item value not exceeding knapsack capacity is " + res);
|
||||
System.out.println("Maximum total item value within the knapsack capacity: " + res);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = knapsackDPComp(wgt, val, cap);
|
||||
System.out.println("Maximum item value not exceeding knapsack capacity is " + res);
|
||||
System.out.println("Maximum total item value within the knapsack capacity: " + res);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,24 +9,24 @@ package chapter_dynamic_programming;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class min_cost_climbing_stairs_dp {
|
||||
/* Minimum cost climbing stairs: Dynamic programming */
|
||||
/* Minimum cost to climb stairs: dynamic programming */
|
||||
public static int minCostClimbingStairsDP(int[] cost) {
|
||||
int n = cost.length - 1;
|
||||
if (n == 1 || n == 2)
|
||||
return cost[n];
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
// Initialize the dp table to store subproblem solutions
|
||||
int[] dp = new int[n + 1];
|
||||
// Initial state: preset the solution to the smallest subproblem
|
||||
// Initial states: set the solutions to the smallest subproblems
|
||||
dp[1] = cost[1];
|
||||
dp[2] = cost[2];
|
||||
// State transition: gradually solve larger subproblems from smaller ones
|
||||
// State transitions: solve progressively larger subproblems using smaller ones
|
||||
for (int i = 3; i <= n; i++) {
|
||||
dp[i] = Math.min(dp[i - 1], dp[i - 2]) + cost[i];
|
||||
}
|
||||
return dp[n];
|
||||
}
|
||||
|
||||
/* Minimum cost climbing stairs: Space-optimized dynamic programming */
|
||||
/* Minimum cost to climb stairs: space-optimized dynamic programming */
|
||||
public static int minCostClimbingStairsDPComp(int[] cost) {
|
||||
int n = cost.length - 1;
|
||||
if (n == 1 || n == 2)
|
||||
@@ -42,12 +42,12 @@ public class min_cost_climbing_stairs_dp {
|
||||
|
||||
public static void main(String[] args) {
|
||||
int[] cost = { 0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1 };
|
||||
System.out.println(String.format("Input staircase cost list is %s", Arrays.toString(cost)));
|
||||
System.out.println(String.format("Input stair costs: %s", Arrays.toString(cost)));
|
||||
|
||||
int res = minCostClimbingStairsDP(cost);
|
||||
System.out.println(String.format("Minimum cost to climb staircase is %d", res));
|
||||
System.out.println(String.format("Minimum cost to climb the stairs: %d", res));
|
||||
|
||||
res = minCostClimbingStairsDPComp(cost);
|
||||
System.out.println(String.format("Minimum cost to climb staircase is %d", res));
|
||||
System.out.println(String.format("Minimum cost to climb the stairs: %d", res));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,60 +9,60 @@ package chapter_dynamic_programming;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class min_path_sum {
|
||||
/* Minimum path sum: Brute-force search */
|
||||
/* Minimum path sum: brute-force search */
|
||||
static int minPathSumDFS(int[][] grid, int i, int j) {
|
||||
// If it's the top-left cell, terminate the search
|
||||
// Stop searching at the top-left cell
|
||||
if (i == 0 && j == 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// If row or column index is out of bounds, return +∞ cost
|
||||
// If a row or column index is out of bounds, return a cost of +∞
|
||||
if (i < 0 || j < 0) {
|
||||
return Integer.MAX_VALUE;
|
||||
}
|
||||
// Calculate the minimum path cost from top-left to (i-1, j) and (i, j-1)
|
||||
// Calculate the minimum path costs from the top-left corner to (i-1, j) and (i, j-1)
|
||||
int up = minPathSumDFS(grid, i - 1, j);
|
||||
int left = minPathSumDFS(grid, i, j - 1);
|
||||
// Return the minimum path cost from top-left to (i, j)
|
||||
// Return the minimum path cost from the top-left corner to (i, j)
|
||||
return Math.min(left, up) + grid[i][j];
|
||||
}
|
||||
|
||||
/* Minimum path sum: Memoization search */
|
||||
/* Minimum path sum: memoized search */
|
||||
static int minPathSumDFSMem(int[][] grid, int[][] mem, int i, int j) {
|
||||
// If it's the top-left cell, terminate the search
|
||||
// Stop searching at the top-left cell
|
||||
if (i == 0 && j == 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// If row or column index is out of bounds, return +∞ cost
|
||||
// If a row or column index is out of bounds, return a cost of +∞
|
||||
if (i < 0 || j < 0) {
|
||||
return Integer.MAX_VALUE;
|
||||
}
|
||||
// If there's a record, return it directly
|
||||
// If a result has already been recorded, return it directly
|
||||
if (mem[i][j] != -1) {
|
||||
return mem[i][j];
|
||||
}
|
||||
// Minimum path cost for left and upper cells
|
||||
// Minimum path costs to the cells on the left and above
|
||||
int up = minPathSumDFSMem(grid, mem, i - 1, j);
|
||||
int left = minPathSumDFSMem(grid, mem, i, j - 1);
|
||||
// Record and return the minimum path cost from top-left to (i, j)
|
||||
// Record and return the minimum path cost from the top-left corner to (i, j)
|
||||
mem[i][j] = Math.min(left, up) + grid[i][j];
|
||||
return mem[i][j];
|
||||
}
|
||||
|
||||
/* Minimum path sum: Dynamic programming */
|
||||
/* Minimum path sum: dynamic programming */
|
||||
static int minPathSumDP(int[][] grid) {
|
||||
int n = grid.length, m = grid[0].length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
int[][] dp = new int[n][m];
|
||||
dp[0][0] = grid[0][0];
|
||||
// State transition: first row
|
||||
// State transitions: first row
|
||||
for (int j = 1; j < m; j++) {
|
||||
dp[0][j] = dp[0][j - 1] + grid[0][j];
|
||||
}
|
||||
// State transition: first column
|
||||
// State transitions: first column
|
||||
for (int i = 1; i < n; i++) {
|
||||
dp[i][0] = dp[i - 1][0] + grid[i][0];
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
// State transitions: remaining rows and columns
|
||||
for (int i = 1; i < n; i++) {
|
||||
for (int j = 1; j < m; j++) {
|
||||
dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
|
||||
@@ -71,21 +71,21 @@ public class min_path_sum {
|
||||
return dp[n - 1][m - 1];
|
||||
}
|
||||
|
||||
/* Minimum path sum: Space-optimized dynamic programming */
|
||||
/* Minimum path sum: space-optimized dynamic programming */
|
||||
static int minPathSumDPComp(int[][] grid) {
|
||||
int n = grid.length, m = grid[0].length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
int[] dp = new int[m];
|
||||
// State transition: first row
|
||||
// State transitions: first row
|
||||
dp[0] = grid[0][0];
|
||||
for (int j = 1; j < m; j++) {
|
||||
dp[j] = dp[j - 1] + grid[0][j];
|
||||
}
|
||||
// State transition: rest of the rows
|
||||
// State transitions: remaining rows
|
||||
for (int i = 1; i < n; i++) {
|
||||
// State transition: first column
|
||||
// State transitions: first column
|
||||
dp[0] = dp[0] + grid[i][0];
|
||||
// State transition: rest of the columns
|
||||
// State transitions: remaining columns
|
||||
for (int j = 1; j < m; j++) {
|
||||
dp[j] = Math.min(dp[j - 1], dp[j]) + grid[i][j];
|
||||
}
|
||||
@@ -104,22 +104,22 @@ public class min_path_sum {
|
||||
|
||||
// Brute-force search
|
||||
int res = minPathSumDFS(grid, n - 1, m - 1);
|
||||
System.out.println("Minimum path sum from top-left to bottom-right is " + res);
|
||||
System.out.println("Minimum path sum from the top-left to the bottom-right corner: " + res);
|
||||
|
||||
// Memoization search
|
||||
// Memoized search
|
||||
int[][] mem = new int[n][m];
|
||||
for (int[] row : mem) {
|
||||
Arrays.fill(row, -1);
|
||||
}
|
||||
res = minPathSumDFSMem(grid, mem, n - 1, m - 1);
|
||||
System.out.println("Minimum path sum from top-left to bottom-right is " + res);
|
||||
System.out.println("Minimum path sum from the top-left to the bottom-right corner: " + res);
|
||||
|
||||
// Dynamic programming
|
||||
res = minPathSumDP(grid);
|
||||
System.out.println("Minimum path sum from top-left to bottom-right is " + res);
|
||||
System.out.println("Minimum path sum from the top-left to the bottom-right corner: " + res);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = minPathSumDPComp(grid);
|
||||
System.out.println("Minimum path sum from top-left to bottom-right is " + res);
|
||||
System.out.println("Minimum path sum from the top-left to the bottom-right corner: " + res);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,19 +7,19 @@
|
||||
package chapter_dynamic_programming;
|
||||
|
||||
public class unbounded_knapsack {
|
||||
/* Unbounded knapsack: Dynamic programming */
|
||||
/* Unbounded knapsack: dynamic programming */
|
||||
static int unboundedKnapsackDP(int[] wgt, int[] val, int cap) {
|
||||
int n = wgt.length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
int[][] dp = new int[n + 1][cap + 1];
|
||||
// State transition
|
||||
// State transitions
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int c = 1; c <= cap; c++) {
|
||||
if (wgt[i - 1] > c) {
|
||||
// If exceeds knapsack capacity, don't select item i
|
||||
// If item i exceeds the remaining capacity, do not choose it
|
||||
dp[i][c] = dp[i - 1][c];
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
dp[i][c] = Math.max(dp[i - 1][c], dp[i][c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
@@ -27,19 +27,19 @@ public class unbounded_knapsack {
|
||||
return dp[n][cap];
|
||||
}
|
||||
|
||||
/* Unbounded knapsack: Space-optimized dynamic programming */
|
||||
/* Unbounded knapsack: space-optimized dynamic programming */
|
||||
static int unboundedKnapsackDPComp(int[] wgt, int[] val, int cap) {
|
||||
int n = wgt.length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
int[] dp = new int[cap + 1];
|
||||
// State transition
|
||||
// State transitions
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int c = 1; c <= cap; c++) {
|
||||
if (wgt[i - 1] > c) {
|
||||
// If exceeds knapsack capacity, don't select item i
|
||||
// If item i exceeds the remaining capacity, do not choose it
|
||||
dp[c] = dp[c];
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
dp[c] = Math.max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
@@ -54,10 +54,10 @@ public class unbounded_knapsack {
|
||||
|
||||
// Dynamic programming
|
||||
int res = unboundedKnapsackDP(wgt, val, cap);
|
||||
System.out.println("Maximum item value not exceeding knapsack capacity is " + res);
|
||||
System.out.println("Maximum total item value within the knapsack capacity: " + res);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = unboundedKnapsackDPComp(wgt, val, cap);
|
||||
System.out.println("Maximum item value not exceeding knapsack capacity is " + res);
|
||||
System.out.println("Maximum total item value within the knapsack capacity: " + res);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user