mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-22 03:32:42 +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:
@@ -9,25 +9,25 @@ namespace hello_algo.chapter_dynamic_programming;
|
||||
public class climbing_stairs_backtrack {
|
||||
/* Backtracking */
|
||||
void Backtrack(List<int> choices, int state, int n, List<int> 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[0]++;
|
||||
// Traverse all choices
|
||||
// Iterate over all choices
|
||||
foreach (int choice in 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 */
|
||||
int ClimbingStairsBacktrack(int n) {
|
||||
List<int> choices = [1, 2]; // Can choose to climb up 1 or 2 stairs
|
||||
int state = 0; // Start climbing from the 0-th stair
|
||||
List<int> res = [0]; // Use res[0] to record the solution count
|
||||
List<int> choices = [1, 2]; // Choose to climb 1 or 2 steps
|
||||
int state = 0; // Start climbing from step 0
|
||||
List<int> res = [0]; // Use res[0] to record the number of ways
|
||||
Backtrack(choices, state, n, res);
|
||||
return res[0];
|
||||
}
|
||||
@@ -36,6 +36,6 @@ public class climbing_stairs_backtrack {
|
||||
public void Test() {
|
||||
int n = 9;
|
||||
int res = ClimbingStairsBacktrack(n);
|
||||
Console.WriteLine($"Climbing {n} stairs has {res} solutions");
|
||||
Console.WriteLine($"Number of ways to climb {n} stairs: {res}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,19 +7,19 @@
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class climbing_stairs_constraint_dp {
|
||||
/* Climbing stairs with constraint: Dynamic programming */
|
||||
/* Climbing stairs with constraints: dynamic programming */
|
||||
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 {
|
||||
public void Test() {
|
||||
int n = 9;
|
||||
int res = ClimbingStairsConstraintDP(n);
|
||||
Console.WriteLine($"Climbing {n} stairs has {res} solutions");
|
||||
Console.WriteLine($"Number of ways to climb {n} stairs: {res}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ namespace hello_algo.chapter_dynamic_programming;
|
||||
public class climbing_stairs_dfs {
|
||||
/* Search */
|
||||
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 */
|
||||
int ClimbingStairsDFS(int n) {
|
||||
return DFS(n);
|
||||
}
|
||||
@@ -26,6 +26,6 @@ public class climbing_stairs_dfs {
|
||||
public void Test() {
|
||||
int n = 9;
|
||||
int res = ClimbingStairsDFS(n);
|
||||
Console.WriteLine($"Climbing {n} stairs has {res} solutions");
|
||||
Console.WriteLine($"Number of ways to climb {n} stairs: {res}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,12 +7,12 @@
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class climbing_stairs_dfs_mem {
|
||||
/* Memoization search */
|
||||
/* Memoized search */
|
||||
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]
|
||||
@@ -22,9 +22,9 @@ public class climbing_stairs_dfs_mem {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Climbing stairs: Memoization search */
|
||||
/* Climbing stairs: memoized search */
|
||||
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];
|
||||
Array.Fill(mem, -1);
|
||||
return DFS(n, mem);
|
||||
@@ -34,6 +34,6 @@ public class climbing_stairs_dfs_mem {
|
||||
public void Test() {
|
||||
int n = 9;
|
||||
int res = ClimbingStairsDFSMem(n);
|
||||
Console.WriteLine($"Climbing {n} stairs has {res} solutions");
|
||||
Console.WriteLine($"Number of ways to climb {n} stairs: {res}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,23 +7,23 @@
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class climbing_stairs_dp {
|
||||
/* Climbing stairs: Dynamic programming */
|
||||
/* Climbing stairs: dynamic programming */
|
||||
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 */
|
||||
int ClimbingStairsDPComp(int n) {
|
||||
if (n == 1 || n == 2)
|
||||
return n;
|
||||
@@ -41,9 +41,9 @@ public class climbing_stairs_dp {
|
||||
int n = 9;
|
||||
|
||||
int res = ClimbingStairsDP(n);
|
||||
Console.WriteLine($"Climbing {n} stairs has {res} solutions");
|
||||
Console.WriteLine($"Number of ways to climb {n} stairs: {res}");
|
||||
|
||||
res = ClimbingStairsDPComp(n);
|
||||
Console.WriteLine($"Climbing {n} stairs has {res} solutions");
|
||||
Console.WriteLine($"Number of ways to climb {n} stairs: {res}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,24 +7,24 @@
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class coin_change {
|
||||
/* Coin change: Dynamic programming */
|
||||
/* Coin change: dynamic programming */
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -32,22 +32,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 */
|
||||
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];
|
||||
Array.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);
|
||||
}
|
||||
}
|
||||
@@ -62,10 +62,10 @@ public class coin_change {
|
||||
|
||||
// Dynamic programming
|
||||
int res = CoinChangeDP(coins, amt);
|
||||
Console.WriteLine("Minimum number of coins needed to make target amount is " + res);
|
||||
Console.WriteLine("Minimum number of coins needed to make the target amount: " + res);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = CoinChangeDPComp(coins, amt);
|
||||
Console.WriteLine("Minimum number of coins needed to make target amount is " + res);
|
||||
Console.WriteLine("Minimum number of coins needed to make the target amount: " + res);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,23 +7,23 @@
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class coin_change_ii {
|
||||
/* Coin change II: Dynamic programming */
|
||||
/* Coin change II: dynamic programming */
|
||||
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 */
|
||||
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]];
|
||||
}
|
||||
}
|
||||
@@ -59,10 +59,10 @@ public class coin_change_ii {
|
||||
|
||||
// Dynamic programming
|
||||
int res = CoinChangeIIDP(coins, amt);
|
||||
Console.WriteLine("Number of coin combinations to make target amount is " + res);
|
||||
Console.WriteLine("Number of coin combinations that make the target amount: " + res);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = CoinChangeIIDPComp(coins, amt);
|
||||
Console.WriteLine("Number of coin combinations to make target amount is " + res);
|
||||
Console.WriteLine("Number of coin combinations that make the target amount: " + res);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,73 +7,73 @@
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class edit_distance {
|
||||
/* Edit distance: Brute-force search */
|
||||
/* Edit distance: brute-force search */
|
||||
int EditDistanceDFS(string s, string t, int i, int j) {
|
||||
// If both s and t are empty, return 0
|
||||
// If both prefixes of s and t are empty, return 0
|
||||
if (i == 0 && j == 0)
|
||||
return 0;
|
||||
// If s is empty, return length of t
|
||||
// If the prefix of s is empty, return the prefix length of t
|
||||
if (i == 0)
|
||||
return j;
|
||||
// If t is empty, return length of s
|
||||
// If the prefix of t is empty, return the prefix length 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[i - 1] == t[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 */
|
||||
int EditDistanceDFSMem(string s, string t, int[][] mem, int i, int j) {
|
||||
// If both s and t are empty, return 0
|
||||
// If both prefixes of s and t are empty, return 0
|
||||
if (i == 0 && j == 0)
|
||||
return 0;
|
||||
// If s is empty, return length of t
|
||||
// If the prefix of s is empty, return the prefix length of t
|
||||
if (i == 0)
|
||||
return j;
|
||||
// If t is empty, return length of s
|
||||
// If the prefix of t is empty, return the prefix length 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[i - 1] == t[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 */
|
||||
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[i - 1] == t[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;
|
||||
}
|
||||
}
|
||||
@@ -81,30 +81,30 @@ public class edit_distance {
|
||||
return dp[n, m];
|
||||
}
|
||||
|
||||
/* Edit distance: Space-optimized dynamic programming */
|
||||
/* Edit distance: space-optimized dynamic programming */
|
||||
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[i - 1] == t[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];
|
||||
@@ -118,9 +118,9 @@ public class edit_distance {
|
||||
|
||||
// Brute-force search
|
||||
int res = EditDistanceDFS(s, t, n, m);
|
||||
Console.WriteLine("Change " + s + " to " + t + " requires a minimum of " + res + " edits");
|
||||
Console.WriteLine("Changing " + s + " to " + t + " requires at least " + res + " edits");
|
||||
|
||||
// Memoization search
|
||||
// Memoized search
|
||||
int[][] mem = new int[n + 1][];
|
||||
for (int i = 0; i <= n; i++) {
|
||||
mem[i] = new int[m + 1];
|
||||
@@ -128,14 +128,14 @@ public class edit_distance {
|
||||
}
|
||||
|
||||
res = EditDistanceDFSMem(s, t, mem, n, m);
|
||||
Console.WriteLine("Change " + s + " to " + t + " requires a minimum of " + res + " edits");
|
||||
Console.WriteLine("Changing " + s + " to " + t + " requires at least " + res + " edits");
|
||||
|
||||
// Dynamic programming
|
||||
res = EditDistanceDP(s, t);
|
||||
Console.WriteLine("Change " + s + " to " + t + " requires a minimum of " + res + " edits");
|
||||
Console.WriteLine("Changing " + s + " to " + t + " requires at least " + res + " edits");
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = EditDistanceDPComp(s, t);
|
||||
Console.WriteLine("Change " + s + " to " + t + " requires a minimum of " + res + " edits");
|
||||
Console.WriteLine("Changing " + s + " to " + t + " requires at least " + res + " edits");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,58 +7,58 @@
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class knapsack {
|
||||
/* 0-1 knapsack: Brute-force search */
|
||||
/* 0-1 knapsack: brute-force search */
|
||||
int KnapsackDFS(int[] weight, 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 (weight[i - 1] > c) {
|
||||
return KnapsackDFS(weight, 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(weight, val, i - 1, c);
|
||||
int yes = KnapsackDFS(weight, val, i - 1, c - weight[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 */
|
||||
int KnapsackDFSMem(int[] weight, 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 (weight[i - 1] > c) {
|
||||
return KnapsackDFSMem(weight, 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(weight, val, mem, i - 1, c);
|
||||
int yes = KnapsackDFSMem(weight, val, mem, i - 1, c - weight[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 */
|
||||
int KnapsackDP(int[] weight, int[] val, int cap) {
|
||||
int n = weight.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 (weight[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 - weight[i - 1]] + val[i - 1], dp[i - 1, c]);
|
||||
}
|
||||
}
|
||||
@@ -66,20 +66,20 @@ public class knapsack {
|
||||
return dp[n, cap];
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Space-optimized dynamic programming */
|
||||
/* 0-1 knapsack: space-optimized dynamic programming */
|
||||
int KnapsackDPComp(int[] weight, int[] val, int cap) {
|
||||
int n = weight.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 > 0; c--) {
|
||||
if (weight[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 - weight[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
@@ -96,23 +96,23 @@ public class knapsack {
|
||||
|
||||
// Brute-force search
|
||||
int res = KnapsackDFS(weight, val, n, cap);
|
||||
Console.WriteLine("Maximum item value not exceeding knapsack capacity is " + res);
|
||||
Console.WriteLine("Maximum total item value within the knapsack capacity: " + res);
|
||||
|
||||
// Memoization search
|
||||
// Memoized search
|
||||
int[][] mem = new int[n + 1][];
|
||||
for (int i = 0; i <= n; i++) {
|
||||
mem[i] = new int[cap + 1];
|
||||
Array.Fill(mem[i], -1);
|
||||
}
|
||||
res = KnapsackDFSMem(weight, val, mem, n, cap);
|
||||
Console.WriteLine("Maximum item value not exceeding knapsack capacity is " + res);
|
||||
Console.WriteLine("Maximum total item value within the knapsack capacity: " + res);
|
||||
|
||||
// Dynamic programming
|
||||
res = KnapsackDP(weight, val, cap);
|
||||
Console.WriteLine("Maximum item value not exceeding knapsack capacity is " + res);
|
||||
Console.WriteLine("Maximum total item value within the knapsack capacity: " + res);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = KnapsackDPComp(weight, val, cap);
|
||||
Console.WriteLine("Maximum item value not exceeding knapsack capacity is " + res);
|
||||
Console.WriteLine("Maximum total item value within the knapsack capacity: " + res);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,24 +7,24 @@
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class min_cost_climbing_stairs_dp {
|
||||
/* Minimum cost climbing stairs: Dynamic programming */
|
||||
/* Minimum cost to climb stairs: dynamic programming */
|
||||
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 */
|
||||
int MinCostClimbingStairsDPComp(int[] cost) {
|
||||
int n = cost.Length - 1;
|
||||
if (n == 1 || n == 2)
|
||||
@@ -41,13 +41,13 @@ public class min_cost_climbing_stairs_dp {
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] cost = [0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1];
|
||||
Console.WriteLine("Input stair cost list is");
|
||||
Console.WriteLine("Input stair costs:");
|
||||
PrintUtil.PrintList(cost);
|
||||
|
||||
int res = MinCostClimbingStairsDP(cost);
|
||||
Console.WriteLine($"Minimum cost to climb stairs is {res}");
|
||||
Console.WriteLine($"Minimum cost to finish climbing the stairs: {res}");
|
||||
|
||||
res = MinCostClimbingStairsDPComp(cost);
|
||||
Console.WriteLine($"Minimum cost to climb stairs is {res}");
|
||||
Console.WriteLine($"Minimum cost to finish climbing the stairs: {res}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,60 +7,60 @@
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class min_path_sum {
|
||||
/* Minimum path sum: Brute-force search */
|
||||
/* Minimum path sum: brute-force search */
|
||||
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 int.MaxValue;
|
||||
}
|
||||
// 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 */
|
||||
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 int.MaxValue;
|
||||
}
|
||||
// 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 */
|
||||
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];
|
||||
@@ -69,21 +69,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 */
|
||||
int MinPathSumDPComp(int[][] grid) {
|
||||
int n = grid.Length, m = grid[0].Length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
int[] dp = new int[m];
|
||||
dp[0] = grid[0][0];
|
||||
// State transition: first row
|
||||
// State transitions: first row
|
||||
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];
|
||||
}
|
||||
@@ -105,23 +105,23 @@ public class min_path_sum {
|
||||
|
||||
// Brute-force search
|
||||
int res = MinPathSumDFS(grid, n - 1, m - 1);
|
||||
Console.WriteLine("Minimum path sum from top-left to bottom-right is " + res);
|
||||
Console.WriteLine("Minimum path sum from the top-left to the bottom-right corner: " + res);
|
||||
|
||||
// Memoization search
|
||||
// Memoized search
|
||||
int[][] mem = new int[n][];
|
||||
for (int i = 0; i < n; i++) {
|
||||
mem[i] = new int[m];
|
||||
Array.Fill(mem[i], -1);
|
||||
}
|
||||
res = MinPathSumDFSMem(grid, mem, n - 1, m - 1);
|
||||
Console.WriteLine("Minimum path sum from top-left to bottom-right is " + res);
|
||||
Console.WriteLine("Minimum path sum from the top-left to the bottom-right corner: " + res);
|
||||
|
||||
// Dynamic programming
|
||||
res = MinPathSumDP(grid);
|
||||
Console.WriteLine("Minimum path sum from top-left to bottom-right is " + res);
|
||||
Console.WriteLine("Minimum path sum from the top-left to the bottom-right corner: " + res);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = MinPathSumDPComp(grid);
|
||||
Console.WriteLine("Minimum path sum from top-left to bottom-right is " + res);
|
||||
Console.WriteLine("Minimum path sum from the top-left to the bottom-right corner: " + res);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,19 +7,19 @@
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class unbounded_knapsack {
|
||||
/* Unbounded knapsack: Dynamic programming */
|
||||
/* Unbounded knapsack: dynamic programming */
|
||||
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 */
|
||||
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]);
|
||||
}
|
||||
}
|
||||
@@ -55,10 +55,10 @@ public class unbounded_knapsack {
|
||||
|
||||
// Dynamic programming
|
||||
int res = UnboundedKnapsackDP(wgt, val, cap);
|
||||
Console.WriteLine("Maximum item value not exceeding knapsack capacity is " + res);
|
||||
Console.WriteLine("Maximum total item value within the knapsack capacity: " + res);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = UnboundedKnapsackDPComp(wgt, val, cap);
|
||||
Console.WriteLine("Maximum item value not exceeding knapsack capacity is " + res);
|
||||
Console.WriteLine("Maximum total item value within the knapsack capacity: " + res);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user