mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-28 23:34:43 +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:
@@ -6,36 +6,36 @@
|
||||
|
||||
/* Backtracking */
|
||||
fn backtrack(choices: &[i32], state: i32, n: i32, res: &mut [i32]) {
|
||||
// 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] = res[0] + 1;
|
||||
}
|
||||
// Traverse all choices
|
||||
// Iterate over all choices
|
||||
for &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 */
|
||||
fn climbing_stairs_backtrack(n: usize) -> i32 {
|
||||
let choices = vec![1, 2]; // Can choose to climb up 1 or 2 stairs
|
||||
let state = 0; // Start climbing from the 0-th stair
|
||||
let choices = vec![1, 2]; // Choose to climb 1 or 2 steps
|
||||
let state = 0; // Start climbing from step 0
|
||||
let mut res = Vec::new();
|
||||
res.push(0); // Use res[0] to record the solution count
|
||||
res.push(0); // Use res[0] to record the number of ways
|
||||
backtrack(&choices, state, n as i32, &mut res);
|
||||
res[0]
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
pub fn main() {
|
||||
let n: usize = 9;
|
||||
|
||||
let res = climbing_stairs_backtrack(n);
|
||||
println!("Climbing {n} stairs has {res} solutions");
|
||||
println!("Number of ways to climb {n} stairs: {res}");
|
||||
}
|
||||
|
||||
@@ -4,19 +4,19 @@
|
||||
* Author: codingonion (coderonion@gmail.com)
|
||||
*/
|
||||
|
||||
/* Climbing stairs with constraint: Dynamic programming */
|
||||
/* Climbing stairs with constraints: dynamic programming */
|
||||
fn climbing_stairs_constraint_dp(n: usize) -> i32 {
|
||||
if n == 1 || n == 2 {
|
||||
return 1;
|
||||
};
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
// Initialize the dp table to store subproblem solutions
|
||||
let mut dp = vec![vec![-1; 3]; n + 1];
|
||||
// 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 i in 3..=n {
|
||||
dp[i][1] = dp[i - 1][2];
|
||||
dp[i][2] = dp[i - 2][1] + dp[i - 2][2];
|
||||
@@ -24,10 +24,10 @@ fn climbing_stairs_constraint_dp(n: usize) -> i32 {
|
||||
dp[n][1] + dp[n][2]
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
pub fn main() {
|
||||
let n: usize = 9;
|
||||
|
||||
let res = climbing_stairs_constraint_dp(n);
|
||||
println!("Climbing {n} stairs has {res} solutions");
|
||||
println!("Number of ways to climb {n} stairs: {res}");
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
/* Search */
|
||||
fn dfs(i: usize) -> i32 {
|
||||
// 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 as i32;
|
||||
}
|
||||
@@ -15,15 +15,15 @@ fn dfs(i: usize) -> i32 {
|
||||
count
|
||||
}
|
||||
|
||||
/* Climbing stairs: Search */
|
||||
/* Climbing stairs: search */
|
||||
fn climbing_stairs_dfs(n: usize) -> i32 {
|
||||
dfs(n)
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
pub fn main() {
|
||||
let n: usize = 9;
|
||||
|
||||
let res = climbing_stairs_dfs(n);
|
||||
println!("Climbing {n} stairs has {res} solutions");
|
||||
println!("Number of ways to climb {n} stairs: {res}");
|
||||
}
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
* Author: codingonion (coderonion@gmail.com)
|
||||
*/
|
||||
|
||||
/* Memoization search */
|
||||
/* Memoized search */
|
||||
fn dfs(i: usize, mem: &mut [i32]) -> i32 {
|
||||
// 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 as i32;
|
||||
}
|
||||
// If record dp[i] exists, return it directly
|
||||
// If dp[i] has been recorded, return it directly
|
||||
if mem[i] != -1 {
|
||||
return mem[i];
|
||||
}
|
||||
@@ -21,17 +21,17 @@ fn dfs(i: usize, mem: &mut [i32]) -> i32 {
|
||||
count
|
||||
}
|
||||
|
||||
/* Climbing stairs: Memoization search */
|
||||
/* Climbing stairs: memoized search */
|
||||
fn climbing_stairs_dfs_mem(n: usize) -> i32 {
|
||||
// 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
|
||||
let mut mem = vec![-1; n + 1];
|
||||
dfs(n, &mut mem)
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
pub fn main() {
|
||||
let n: usize = 9;
|
||||
|
||||
let res = climbing_stairs_dfs_mem(n);
|
||||
println!("Climbing {n} stairs has {res} solutions");
|
||||
println!("Number of ways to climb {n} stairs: {res}");
|
||||
}
|
||||
|
||||
@@ -4,25 +4,25 @@
|
||||
* Author: codingonion (coderonion@gmail.com)
|
||||
*/
|
||||
|
||||
/* Climbing stairs: Dynamic programming */
|
||||
/* Climbing stairs: dynamic programming */
|
||||
fn climbing_stairs_dp(n: usize) -> i32 {
|
||||
// Known dp[1] and dp[2], return them
|
||||
// The values of dp[1] and dp[2] are known; return them
|
||||
if n == 1 || n == 2 {
|
||||
return n as i32;
|
||||
}
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
// Initialize the dp table to store subproblem solutions
|
||||
let mut dp = vec![-1; 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 i in 3..=n {
|
||||
dp[i] = dp[i - 1] + dp[i - 2];
|
||||
}
|
||||
dp[n]
|
||||
}
|
||||
|
||||
/* Climbing stairs: Space-optimized dynamic programming */
|
||||
/* Climbing stairs: space-optimized dynamic programming */
|
||||
fn climbing_stairs_dp_comp(n: usize) -> i32 {
|
||||
if n == 1 || n == 2 {
|
||||
return n as i32;
|
||||
@@ -36,13 +36,13 @@ fn climbing_stairs_dp_comp(n: usize) -> i32 {
|
||||
b
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
pub fn main() {
|
||||
let n: usize = 9;
|
||||
|
||||
let res = climbing_stairs_dp(n);
|
||||
println!("Climbing {n} stairs has {res} solutions");
|
||||
println!("Number of ways to climb {n} stairs: {res}");
|
||||
|
||||
let res = climbing_stairs_dp_comp(n);
|
||||
println!("Climbing {n} stairs has {res} solutions");
|
||||
println!("Number of ways to climb {n} stairs: {res}");
|
||||
}
|
||||
|
||||
@@ -4,24 +4,24 @@
|
||||
* Author: codingonion (coderonion@gmail.com)
|
||||
*/
|
||||
|
||||
/* Coin change: Dynamic programming */
|
||||
/* Coin change: dynamic programming */
|
||||
fn coin_change_dp(coins: &[i32], amt: usize) -> i32 {
|
||||
let n = coins.len();
|
||||
let max = amt + 1;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
let mut dp = vec![vec![0; amt + 1]; n + 1];
|
||||
// State transition: first row and first column
|
||||
// State transitions: first row and first column
|
||||
for a in 1..=amt {
|
||||
dp[0][a] = max;
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
// State transitions: remaining rows and columns
|
||||
for i in 1..=n {
|
||||
for a in 1..=amt {
|
||||
if coins[i - 1] > a as i32 {
|
||||
// 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] = std::cmp::min(dp[i - 1][a], dp[i][a - coins[i - 1] as usize] + 1);
|
||||
}
|
||||
}
|
||||
@@ -33,22 +33,22 @@ fn coin_change_dp(coins: &[i32], amt: usize) -> i32 {
|
||||
}
|
||||
}
|
||||
|
||||
/* Coin change: Space-optimized dynamic programming */
|
||||
/* Coin change: space-optimized dynamic programming */
|
||||
fn coin_change_dp_comp(coins: &[i32], amt: usize) -> i32 {
|
||||
let n = coins.len();
|
||||
let max = amt + 1;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
let mut dp = vec![0; amt + 1];
|
||||
dp.fill(max);
|
||||
dp[0] = 0;
|
||||
// State transition
|
||||
// State transitions
|
||||
for i in 1..=n {
|
||||
for a in 1..=amt {
|
||||
if coins[i - 1] > a as i32 {
|
||||
// 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] = std::cmp::min(dp[a], dp[a - coins[i - 1] as usize] + 1);
|
||||
}
|
||||
}
|
||||
@@ -60,16 +60,16 @@ fn coin_change_dp_comp(coins: &[i32], amt: usize) -> i32 {
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
pub fn main() {
|
||||
let coins = [1, 2, 5];
|
||||
let amt: usize = 4;
|
||||
|
||||
// Dynamic programming
|
||||
let res = coin_change_dp(&coins, amt);
|
||||
println!("Minimum coins needed to make target amount is {res}");
|
||||
println!("Minimum number of coins needed to make the target amount: {res}");
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
let res = coin_change_dp_comp(&coins, amt);
|
||||
println!("Minimum coins needed to make target amount is {res}");
|
||||
println!("Minimum number of coins needed to make the target amount: {res}");
|
||||
}
|
||||
|
||||
@@ -4,23 +4,23 @@
|
||||
* Author: codingonion (coderonion@gmail.com)
|
||||
*/
|
||||
|
||||
/* Coin change II: Dynamic programming */
|
||||
/* Coin change II: dynamic programming */
|
||||
fn coin_change_ii_dp(coins: &[i32], amt: usize) -> i32 {
|
||||
let n = coins.len();
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
let mut dp = vec![vec![0; amt + 1]; n + 1];
|
||||
// Initialize first column
|
||||
// Initialize the first column
|
||||
for i in 0..=n {
|
||||
dp[i][0] = 1;
|
||||
}
|
||||
// State transition
|
||||
// State transitions
|
||||
for i in 1..=n {
|
||||
for a in 1..=amt {
|
||||
if coins[i - 1] > a as i32 {
|
||||
// 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] as usize];
|
||||
}
|
||||
}
|
||||
@@ -28,20 +28,20 @@ fn coin_change_ii_dp(coins: &[i32], amt: usize) -> i32 {
|
||||
dp[n][amt]
|
||||
}
|
||||
|
||||
/* Coin change II: Space-optimized dynamic programming */
|
||||
/* Coin change II: space-optimized dynamic programming */
|
||||
fn coin_change_ii_dp_comp(coins: &[i32], amt: usize) -> i32 {
|
||||
let n = coins.len();
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
let mut dp = vec![0; amt + 1];
|
||||
dp[0] = 1;
|
||||
// State transition
|
||||
// State transitions
|
||||
for i in 1..=n {
|
||||
for a in 1..=amt {
|
||||
if coins[i - 1] > a as i32 {
|
||||
// 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] as usize];
|
||||
}
|
||||
}
|
||||
@@ -49,16 +49,16 @@ fn coin_change_ii_dp_comp(coins: &[i32], amt: usize) -> i32 {
|
||||
dp[amt]
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
pub fn main() {
|
||||
let coins = [1, 2, 5];
|
||||
let amt: usize = 5;
|
||||
|
||||
// Dynamic programming
|
||||
let res = coin_change_ii_dp(&coins, amt);
|
||||
println!("Number of coin combinations to make target amount is {res}");
|
||||
println!("Number of coin combinations that make the target amount: {res}");
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
let res = coin_change_ii_dp_comp(&coins, amt);
|
||||
println!("Number of coin combinations to make target amount is {res}");
|
||||
println!("Number of coin combinations that make the target amount: {res}");
|
||||
}
|
||||
|
||||
@@ -4,82 +4,82 @@
|
||||
* Author: codingonion (coderonion@gmail.com)
|
||||
*/
|
||||
|
||||
/* Edit distance: Brute-force search */
|
||||
/* Edit distance: brute-force search */
|
||||
fn edit_distance_dfs(s: &str, t: &str, i: usize, j: usize) -> i32 {
|
||||
// If both s and t are empty, return 0
|
||||
// If both prefixes 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 length j of the prefix of t
|
||||
if i == 0 {
|
||||
return j as i32;
|
||||
}
|
||||
// If t is empty, return length of s
|
||||
// If the prefix of t is empty, return the length i of the prefix of s
|
||||
if j == 0 {
|
||||
return i as i32;
|
||||
}
|
||||
// If two characters are equal, skip both characters
|
||||
// If the two characters are equal, skip both of them
|
||||
if s.chars().nth(i - 1) == t.chars().nth(j - 1) {
|
||||
return edit_distance_dfs(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
|
||||
let insert = edit_distance_dfs(s, t, i, j - 1);
|
||||
let delete = edit_distance_dfs(s, t, i - 1, j);
|
||||
let replace = edit_distance_dfs(s, t, i - 1, j - 1);
|
||||
// Return minimum edit steps
|
||||
// Return the minimum number of edits
|
||||
std::cmp::min(std::cmp::min(insert, delete), replace) + 1
|
||||
}
|
||||
|
||||
/* Edit distance: Memoization search */
|
||||
/* Edit distance: memoized search */
|
||||
fn edit_distance_dfs_mem(s: &str, t: &str, mem: &mut Vec<Vec<i32>>, i: usize, j: usize) -> i32 {
|
||||
// If both s and t are empty, return 0
|
||||
// If both prefixes 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 length j of the prefix of t
|
||||
if i == 0 {
|
||||
return j as i32;
|
||||
}
|
||||
// If t is empty, return length of s
|
||||
// If the prefix of t is empty, return the length i of the prefix of s
|
||||
if j == 0 {
|
||||
return i as i32;
|
||||
}
|
||||
// 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.chars().nth(i - 1) == t.chars().nth(j - 1) {
|
||||
return edit_distance_dfs_mem(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
|
||||
let insert = edit_distance_dfs_mem(s, t, mem, i, j - 1);
|
||||
let delete = edit_distance_dfs_mem(s, t, mem, i - 1, j);
|
||||
let replace = edit_distance_dfs_mem(s, t, mem, i - 1, j - 1);
|
||||
// Record and return minimum edit steps
|
||||
// Record and return the minimum number of edits
|
||||
mem[i][j] = std::cmp::min(std::cmp::min(insert, delete), replace) + 1;
|
||||
mem[i][j]
|
||||
}
|
||||
|
||||
/* Edit distance: Dynamic programming */
|
||||
/* Edit distance: dynamic programming */
|
||||
fn edit_distance_dp(s: &str, t: &str) -> i32 {
|
||||
let (n, m) = (s.len(), t.len());
|
||||
let mut dp = vec![vec![0; m + 1]; n + 1];
|
||||
// State transition: first row and first column
|
||||
// State transitions: first row and first column
|
||||
for i in 1..=n {
|
||||
dp[i][0] = i as i32;
|
||||
}
|
||||
for j in 1..m {
|
||||
dp[0][j] = j as i32;
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
// State transitions: remaining rows and columns
|
||||
for i in 1..=n {
|
||||
for j in 1..=m {
|
||||
if s.chars().nth(i - 1) == t.chars().nth(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] =
|
||||
std::cmp::min(std::cmp::min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
|
||||
}
|
||||
@@ -88,36 +88,36 @@ fn edit_distance_dp(s: &str, t: &str) -> i32 {
|
||||
dp[n][m]
|
||||
}
|
||||
|
||||
/* Edit distance: Space-optimized dynamic programming */
|
||||
/* Edit distance: space-optimized dynamic programming */
|
||||
fn edit_distance_dp_comp(s: &str, t: &str) -> i32 {
|
||||
let (n, m) = (s.len(), t.len());
|
||||
let mut dp = vec![0; m + 1];
|
||||
// State transition: first row
|
||||
// State transitions: first row
|
||||
for j in 1..m {
|
||||
dp[j] = j as i32;
|
||||
}
|
||||
// State transition: rest of the rows
|
||||
// State transitions: remaining rows
|
||||
for i in 1..=n {
|
||||
// State transition: first column
|
||||
// State transitions: first column
|
||||
let mut leftup = dp[0]; // Temporarily store dp[i-1, j-1]
|
||||
dp[0] = i as i32;
|
||||
// State transition: rest of the columns
|
||||
// State transitions: remaining columns
|
||||
for j in 1..=m {
|
||||
let temp = dp[j];
|
||||
if s.chars().nth(i - 1) == t.chars().nth(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] = std::cmp::min(std::cmp::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
|
||||
}
|
||||
}
|
||||
dp[m]
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
pub fn main() {
|
||||
let s = "bag";
|
||||
let t = "pack";
|
||||
@@ -125,21 +125,21 @@ pub fn main() {
|
||||
|
||||
// Brute-force search
|
||||
let res = edit_distance_dfs(s, t, n, m);
|
||||
println!("Changing {s} to {t} requires minimum {res} edits");
|
||||
println!("Changing {s} to {t} requires at least {res} edits");
|
||||
|
||||
// Memoization search
|
||||
// Memoized search
|
||||
let mut mem = vec![vec![0; m + 1]; n + 1];
|
||||
for row in mem.iter_mut() {
|
||||
row.fill(-1);
|
||||
}
|
||||
let res = edit_distance_dfs_mem(s, t, &mut mem, n, m);
|
||||
println!("Changing {s} to {t} requires minimum {res} edits");
|
||||
println!("Changing {s} to {t} requires at least {res} edits");
|
||||
|
||||
// Dynamic programming
|
||||
let res = edit_distance_dp(s, t);
|
||||
println!("Changing {s} to {t} requires minimum {res} edits");
|
||||
println!("Changing {s} to {t} requires at least {res} edits");
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
let res = edit_distance_dp_comp(s, t);
|
||||
println!("Changing {s} to {t} requires minimum {res} edits");
|
||||
println!("Changing {s} to {t} requires at least {res} edits");
|
||||
}
|
||||
|
||||
@@ -4,58 +4,58 @@
|
||||
* Author: codingonion (coderonion@gmail.com)
|
||||
*/
|
||||
|
||||
/* 0-1 knapsack: Brute-force search */
|
||||
/* 0-1 knapsack: brute-force search */
|
||||
fn knapsack_dfs(wgt: &[i32], val: &[i32], i: usize, c: usize) -> i32 {
|
||||
// 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 as i32 {
|
||||
return knapsack_dfs(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
|
||||
let no = knapsack_dfs(wgt, val, i - 1, c);
|
||||
let yes = knapsack_dfs(wgt, val, i - 1, c - wgt[i - 1] as usize) + val[i - 1];
|
||||
// Return the larger value of the two options
|
||||
// Return the larger value from the two choices
|
||||
std::cmp::max(no, yes)
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Memoization search */
|
||||
/* 0-1 knapsack: memoized search */
|
||||
fn knapsack_dfs_mem(wgt: &[i32], val: &[i32], mem: &mut Vec<Vec<i32>>, i: usize, c: usize) -> i32 {
|
||||
// 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 as i32 {
|
||||
return knapsack_dfs_mem(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
|
||||
let no = knapsack_dfs_mem(wgt, val, mem, i - 1, c);
|
||||
let yes = knapsack_dfs_mem(wgt, val, mem, i - 1, c - wgt[i - 1] as usize) + 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] = std::cmp::max(no, yes);
|
||||
mem[i][c]
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Dynamic programming */
|
||||
/* 0-1 knapsack: dynamic programming */
|
||||
fn knapsack_dp(wgt: &[i32], val: &[i32], cap: usize) -> i32 {
|
||||
let n = wgt.len();
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
let mut dp = vec![vec![0; cap + 1]; n + 1];
|
||||
// State transition
|
||||
// State transitions
|
||||
for i in 1..=n {
|
||||
for c in 1..=cap {
|
||||
if wgt[i - 1] > c as i32 {
|
||||
// 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] = std::cmp::max(
|
||||
dp[i - 1][c],
|
||||
dp[i - 1][c - wgt[i - 1] as usize] + val[i - 1],
|
||||
@@ -66,17 +66,17 @@ fn knapsack_dp(wgt: &[i32], val: &[i32], cap: usize) -> i32 {
|
||||
dp[n][cap]
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Space-optimized dynamic programming */
|
||||
/* 0-1 knapsack: space-optimized dynamic programming */
|
||||
fn knapsack_dp_comp(wgt: &[i32], val: &[i32], cap: usize) -> i32 {
|
||||
let n = wgt.len();
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
let mut dp = vec![0; cap + 1];
|
||||
// State transition
|
||||
// State transitions
|
||||
for i in 1..=n {
|
||||
// Traverse in reverse order
|
||||
// Traverse in decreasing order
|
||||
for c in (1..=cap).rev() {
|
||||
if wgt[i - 1] <= c as i32 {
|
||||
// The larger value between not selecting and selecting item i
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
dp[c] = std::cmp::max(dp[c], dp[c - wgt[i - 1] as usize] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
@@ -84,7 +84,7 @@ fn knapsack_dp_comp(wgt: &[i32], val: &[i32], cap: usize) -> i32 {
|
||||
dp[cap]
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
pub fn main() {
|
||||
let wgt = [10, 20, 30, 40, 50];
|
||||
let val = [50, 120, 150, 210, 240];
|
||||
@@ -93,21 +93,21 @@ pub fn main() {
|
||||
|
||||
// Brute-force search
|
||||
let res = knapsack_dfs(&wgt, &val, n, cap);
|
||||
println!("Maximum item value not exceeding knapsack capacity is {res}");
|
||||
println!("Maximum total item value within the knapsack capacity: {res}");
|
||||
|
||||
// Memoization search
|
||||
// Memoized search
|
||||
let mut mem = vec![vec![0; cap + 1]; n + 1];
|
||||
for row in mem.iter_mut() {
|
||||
row.fill(-1);
|
||||
}
|
||||
let res = knapsack_dfs_mem(&wgt, &val, &mut mem, n, cap);
|
||||
println!("Maximum item value not exceeding knapsack capacity is {res}");
|
||||
println!("Maximum total item value within the knapsack capacity: {res}");
|
||||
|
||||
// Dynamic programming
|
||||
let res = knapsack_dp(&wgt, &val, cap);
|
||||
println!("Maximum item value not exceeding knapsack capacity is {res}");
|
||||
println!("Maximum total item value within the knapsack capacity: {res}");
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
let res = knapsack_dp_comp(&wgt, &val, cap);
|
||||
println!("Maximum item value not exceeding knapsack capacity is {res}");
|
||||
println!("Maximum total item value within the knapsack capacity: {res}");
|
||||
}
|
||||
|
||||
@@ -6,25 +6,25 @@
|
||||
|
||||
use std::cmp;
|
||||
|
||||
/* Minimum cost climbing stairs: Dynamic programming */
|
||||
/* Minimum cost to climb stairs: dynamic programming */
|
||||
fn min_cost_climbing_stairs_dp(cost: &[i32]) -> i32 {
|
||||
let n = cost.len() - 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
|
||||
let mut dp = vec![-1; 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 i in 3..=n {
|
||||
dp[i] = cmp::min(dp[i - 1], dp[i - 2]) + cost[i];
|
||||
}
|
||||
dp[n]
|
||||
}
|
||||
|
||||
/* Minimum cost climbing stairs: Space-optimized dynamic programming */
|
||||
/* Minimum cost to climb stairs: space-optimized dynamic programming */
|
||||
fn min_cost_climbing_stairs_dp_comp(cost: &[i32]) -> i32 {
|
||||
let n = cost.len() - 1;
|
||||
if n == 1 || n == 2 {
|
||||
@@ -39,14 +39,14 @@ fn min_cost_climbing_stairs_dp_comp(cost: &[i32]) -> i32 {
|
||||
b
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
pub fn main() {
|
||||
let cost = [0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1];
|
||||
println!("Input stair cost list is {:?}", &cost);
|
||||
println!("Input stair costs: {:?}", &cost);
|
||||
|
||||
let res = min_cost_climbing_stairs_dp(&cost);
|
||||
println!("Minimum cost to climb stairs is {res}");
|
||||
println!("Minimum cost to finish climbing the stairs: {res}");
|
||||
|
||||
let res = min_cost_climbing_stairs_dp_comp(&cost);
|
||||
println!("Minimum cost to climb stairs is {res}");
|
||||
println!("Minimum cost to finish climbing the stairs: {res}");
|
||||
}
|
||||
|
||||
@@ -4,60 +4,60 @@
|
||||
* Author: codingonion (coderonion@gmail.com)
|
||||
*/
|
||||
|
||||
/* Minimum path sum: Brute-force search */
|
||||
/* Minimum path sum: brute-force search */
|
||||
fn min_path_sum_dfs(grid: &Vec<Vec<i32>>, i: i32, j: i32) -> i32 {
|
||||
// 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 i32::MAX to represent infinite cost
|
||||
if i < 0 || j < 0 {
|
||||
return i32::MAX;
|
||||
}
|
||||
// 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)
|
||||
let up = min_path_sum_dfs(grid, i - 1, j);
|
||||
let left = min_path_sum_dfs(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)
|
||||
std::cmp::min(left, up) + grid[i as usize][j as usize]
|
||||
}
|
||||
|
||||
/* Minimum path sum: Memoization search */
|
||||
/* Minimum path sum: memoized search */
|
||||
fn min_path_sum_dfs_mem(grid: &Vec<Vec<i32>>, mem: &mut Vec<Vec<i32>>, i: i32, j: i32) -> i32 {
|
||||
// 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 i32::MAX to represent infinite cost
|
||||
if i < 0 || j < 0 {
|
||||
return i32::MAX;
|
||||
}
|
||||
// If there's a record, return it directly
|
||||
// If a result has already been recorded, return it directly
|
||||
if mem[i as usize][j as usize] != -1 {
|
||||
return mem[i as usize][j as usize];
|
||||
}
|
||||
// Minimum path cost for left and upper cells
|
||||
// Minimum path costs to the cells on the left and above
|
||||
let up = min_path_sum_dfs_mem(grid, mem, i - 1, j);
|
||||
let left = min_path_sum_dfs_mem(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 as usize][j as usize] = std::cmp::min(left, up) + grid[i as usize][j as usize];
|
||||
mem[i as usize][j as usize]
|
||||
}
|
||||
|
||||
/* Minimum path sum: Dynamic programming */
|
||||
/* Minimum path sum: dynamic programming */
|
||||
fn min_path_sum_dp(grid: &Vec<Vec<i32>>) -> i32 {
|
||||
let (n, m) = (grid.len(), grid[0].len());
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
let mut dp = vec![vec![0; m]; n];
|
||||
dp[0][0] = grid[0][0];
|
||||
// State transition: first row
|
||||
// State transitions: first row
|
||||
for j in 1..m {
|
||||
dp[0][j] = dp[0][j - 1] + grid[0][j];
|
||||
}
|
||||
// State transition: first column
|
||||
// State transitions: first column
|
||||
for i in 1..n {
|
||||
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 i in 1..n {
|
||||
for j in 1..m {
|
||||
dp[i][j] = std::cmp::min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
|
||||
@@ -66,21 +66,21 @@ fn min_path_sum_dp(grid: &Vec<Vec<i32>>) -> i32 {
|
||||
dp[n - 1][m - 1]
|
||||
}
|
||||
|
||||
/* Minimum path sum: Space-optimized dynamic programming */
|
||||
/* Minimum path sum: space-optimized dynamic programming */
|
||||
fn min_path_sum_dp_comp(grid: &Vec<Vec<i32>>) -> i32 {
|
||||
let (n, m) = (grid.len(), grid[0].len());
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
let mut dp = vec![0; m];
|
||||
// State transition: first row
|
||||
// State transitions: first row
|
||||
dp[0] = grid[0][0];
|
||||
for j in 1..m {
|
||||
dp[j] = dp[j - 1] + grid[0][j];
|
||||
}
|
||||
// State transition: rest of the rows
|
||||
// State transitions: remaining rows
|
||||
for i in 1..n {
|
||||
// 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 j in 1..m {
|
||||
dp[j] = std::cmp::min(dp[j - 1], dp[j]) + grid[i][j];
|
||||
}
|
||||
@@ -88,7 +88,7 @@ fn min_path_sum_dp_comp(grid: &Vec<Vec<i32>>) -> i32 {
|
||||
dp[m - 1]
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
pub fn main() {
|
||||
let grid = vec![
|
||||
vec![1, 3, 1, 5],
|
||||
@@ -100,21 +100,21 @@ pub fn main() {
|
||||
|
||||
// Brute-force search
|
||||
let res = min_path_sum_dfs(&grid, n as i32 - 1, m as i32 - 1);
|
||||
println!("Minimum path sum from top-left to bottom-right is {res}");
|
||||
println!("Minimum path sum from the top-left to the bottom-right corner: {res}");
|
||||
|
||||
// Memoization search
|
||||
// Memoized search
|
||||
let mut mem = vec![vec![0; m]; n];
|
||||
for row in mem.iter_mut() {
|
||||
row.fill(-1);
|
||||
}
|
||||
let res = min_path_sum_dfs_mem(&grid, &mut mem, n as i32 - 1, m as i32 - 1);
|
||||
println!("Minimum path sum from top-left to bottom-right is {res}");
|
||||
println!("Minimum path sum from the top-left to the bottom-right corner: {res}");
|
||||
|
||||
// Dynamic programming
|
||||
let res = min_path_sum_dp(&grid);
|
||||
println!("Minimum path sum from top-left to bottom-right is {res}");
|
||||
println!("Minimum path sum from the top-left to the bottom-right corner: {res}");
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
let res = min_path_sum_dp_comp(&grid);
|
||||
println!("Minimum path sum from top-left to bottom-right is {res}");
|
||||
println!("Minimum path sum from the top-left to the bottom-right corner: {res}");
|
||||
}
|
||||
|
||||
@@ -4,19 +4,19 @@
|
||||
* Author: codingonion (coderonion@gmail.com)
|
||||
*/
|
||||
|
||||
/* Unbounded knapsack: Dynamic programming */
|
||||
/* Unbounded knapsack: dynamic programming */
|
||||
fn unbounded_knapsack_dp(wgt: &[i32], val: &[i32], cap: usize) -> i32 {
|
||||
let n = wgt.len();
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
let mut dp = vec![vec![0; cap + 1]; n + 1];
|
||||
// State transition
|
||||
// State transitions
|
||||
for i in 1..=n {
|
||||
for c in 1..=cap {
|
||||
if wgt[i - 1] > c as i32 {
|
||||
// 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] = std::cmp::max(dp[i - 1][c], dp[i][c - wgt[i - 1] as usize] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
@@ -24,19 +24,19 @@ fn unbounded_knapsack_dp(wgt: &[i32], val: &[i32], cap: usize) -> i32 {
|
||||
return dp[n][cap];
|
||||
}
|
||||
|
||||
/* Unbounded knapsack: Space-optimized dynamic programming */
|
||||
/* Unbounded knapsack: space-optimized dynamic programming */
|
||||
fn unbounded_knapsack_dp_comp(wgt: &[i32], val: &[i32], cap: usize) -> i32 {
|
||||
let n = wgt.len();
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
let mut dp = vec![0; cap + 1];
|
||||
// State transition
|
||||
// State transitions
|
||||
for i in 1..=n {
|
||||
for c in 1..=cap {
|
||||
if wgt[i - 1] > c as i32 {
|
||||
// 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] = std::cmp::max(dp[c], dp[c - wgt[i - 1] as usize] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
@@ -44,7 +44,7 @@ fn unbounded_knapsack_dp_comp(wgt: &[i32], val: &[i32], cap: usize) -> i32 {
|
||||
dp[cap]
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
pub fn main() {
|
||||
let wgt = [1, 2, 3];
|
||||
let val = [5, 11, 15];
|
||||
@@ -52,9 +52,9 @@ pub fn main() {
|
||||
|
||||
// Dynamic programming
|
||||
let res = unbounded_knapsack_dp(&wgt, &val, cap);
|
||||
println!("Maximum item value not exceeding knapsack capacity is {res}");
|
||||
println!("Maximum total item value within the knapsack capacity: {res}");
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
let res = unbounded_knapsack_dp_comp(&wgt, &val, cap);
|
||||
println!("Maximum item value not exceeding knapsack capacity is {res}");
|
||||
println!("Maximum total item value within the knapsack capacity: {res}");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user