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:
Yudong Jin
2026-10-31 03:35:51 +08:00
committed by GitHub
parent ef46e2ed95
commit 14c314c08c
1502 changed files with 29459 additions and 23517 deletions

View File

@@ -0,0 +1,44 @@
// File: climbing_stairs_backtrack.zig
// Created Time: 2023-07-15
// Author: codingonion (coderonion@gmail.com)
const std = @import("std");
// Backtracking
fn backtrack(choices: []i32, state: i32, n: i32, res: std.ArrayList(i32)) void {
// When step n is reached, increase the number of ways by 1
if (state == n) {
res.items[0] = res.items[0] + 1;
}
// Iterate over all choices
for (choices) |choice| {
// Prune: do not go beyond step n
if (state + choice > n) {
continue;
}
// Try: make a choice and update the state
backtrack(choices, state + choice, n, res);
// Backtrack
}
}
// Climbing stairs: backtracking
fn climbingStairsBacktrack(n: usize) !i32 {
var choices = [_]i32{ 1, 2 }; // Choose to climb 1 or 2 steps
var state: i32 = 0; // Start climbing from step 0
var res = std.ArrayList(i32).init(std.heap.page_allocator);
defer res.deinit();
try res.append(0); // Use res.items[0] to record the number of solutions
backtrack(&choices, state, @intCast(n), res);
return res.items[0];
}
// Driver code
pub fn main() !void {
var n: usize = 9;
var res = try climbingStairsBacktrack(n);
std.debug.print("Ways to climb {} stairs: {}\n", .{ n, res });
_ = try std.io.getStdIn().reader().readByte();
}

View File

@@ -0,0 +1,35 @@
// File: climbing_stairs_constraint_dp.zig
// Created Time: 2023-07-15
// Author: codingonion (coderonion@gmail.com)
const std = @import("std");
// Climbing stairs with constraints: dynamic programming
fn climbingStairsConstraintDP(comptime n: usize) i32 {
if (n == 1 or n == 2) {
return 1;
}
// Initialize the dp table to store subproblem solutions
var dp = [_][3]i32{ [_]i32{ -1, -1, -1 } } ** (n + 1);
// 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 transitions: solve progressively larger subproblems using smaller ones
for (3..n + 1) |i| {
dp[i][1] = dp[i - 1][2];
dp[i][2] = dp[i - 2][1] + dp[i - 2][2];
}
return dp[n][1] + dp[n][2];
}
// Driver code
pub fn main() !void {
comptime var n: usize = 9;
var res = climbingStairsConstraintDP(n);
std.debug.print("Ways to climb {} stairs: {}\n", .{ n, res });
_ = try std.io.getStdIn().reader().readByte();
}

View File

@@ -0,0 +1,31 @@
// File: climbing_stairs_dfs.zig
// Created Time: 2023-07-15
// Author: codingonion (coderonion@gmail.com)
const std = @import("std");
// Search
fn dfs(i: usize) i32 {
// The values of dp[1] and dp[2] are known; return them
if (i == 1 or i == 2) {
return @intCast(i);
}
// dp[i] = dp[i-1] + dp[i-2]
var count = dfs(i - 1) + dfs(i - 2);
return count;
}
// Climbing stairs: search
fn climbingStairsDFS(comptime n: usize) i32 {
return dfs(n);
}
// Driver code
pub fn main() !void {
comptime var n: usize = 9;
var res = climbingStairsDFS(n);
std.debug.print("Ways to climb {} stairs: {}\n", .{ n, res });
_ = try std.io.getStdIn().reader().readByte();
}

View File

@@ -0,0 +1,39 @@
// File: climbing_stairs_dfs_mem.zig
// Created Time: 2023-07-15
// Author: codingonion (coderonion@gmail.com)
const std = @import("std");
// Memoized search
fn dfs(i: usize, mem: []i32) i32 {
// The values of dp[1] and dp[2] are known; return them
if (i == 1 or i == 2) {
return @intCast(i);
}
// If dp[i] has been recorded, return it directly
if (mem[i] != -1) {
return mem[i];
}
// dp[i] = dp[i-1] + dp[i-2]
var count = dfs(i - 1, mem) + dfs(i - 2, mem);
// Record dp[i]
mem[i] = count;
return count;
}
// Climbing stairs: memoized search
fn climbingStairsDFSMem(comptime n: usize) i32 {
// mem[i] stores the number of ways to reach step i; -1 means no result has been recorded
var mem = [_]i32{ -1 } ** (n + 1);
return dfs(n, &mem);
}
// Driver code
pub fn main() !void {
comptime var n: usize = 9;
var res = climbingStairsDFSMem(n);
std.debug.print("Ways to climb {} stairs: {}\n", .{ n, res });
_ = try std.io.getStdIn().reader().readByte();
}

View File

@@ -0,0 +1,51 @@
// File: climbing_stairs_dp.zig
// Created Time: 2023-07-15
// Author: codingonion (coderonion@gmail.com)
const std = @import("std");
// Climbing stairs: dynamic programming
fn climbingStairsDP(comptime n: usize) i32 {
// The values of dp[1] and dp[2] are known; return them
if (n == 1 or n == 2) {
return @intCast(n);
}
// Initialize the dp table to store subproblem solutions
var dp = [_]i32{-1} ** (n + 1);
// Initial states: set the solutions to the smallest subproblems
dp[1] = 1;
dp[2] = 2;
// State transitions: solve progressively larger subproblems using smaller ones
for (3..n + 1) |i| {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
// Climbing stairs: space-optimized dynamic programming
fn climbingStairsDPComp(comptime n: usize) i32 {
if (n == 1 or n == 2) {
return @intCast(n);
}
var a: i32 = 1;
var b: i32 = 2;
for (3..n + 1) |_| {
var tmp = b;
b = a + b;
a = tmp;
}
return b;
}
// Driver code
pub fn main() !void {
comptime var n: usize = 9;
var res = climbingStairsDP(n);
std.debug.print("Ways to climb {} stairs: {}\n", .{ n, res });
res = climbingStairsDPComp(n);
std.debug.print("Ways to climb {} stairs: {}\n", .{ n, res });
_ = try std.io.getStdIn().reader().readByte();
}

View File

@@ -0,0 +1,77 @@
// File: coin_change.zig
// Created Time: 2023-07-15
// Author: codingonion (coderonion@gmail.com)
const std = @import("std");
// Coin change: dynamic programming
fn coinChangeDP(comptime coins: []i32, comptime amt: usize) i32 {
comptime var n = coins.len;
comptime var max = amt + 1;
// Initialize the dp table
var dp = [_][amt + 1]i32{[_]i32{0} ** (amt + 1)} ** (n + 1);
// State transitions: first row and first column
for (1..amt + 1) |a| {
dp[0][a] = max;
}
// State transitions: remaining rows and columns
for (1..n + 1) |i| {
for (1..amt + 1) |a| {
if (coins[i - 1] > @as(i32, @intCast(a))) {
// If the coin exceeds the target amount, do not choose coin i
dp[i][a] = dp[i - 1][a];
} else {
// Take the smaller result of not choosing and choosing coin i
dp[i][a] = @min(dp[i - 1][a], dp[i][a - @as(usize, @intCast(coins[i - 1]))] + 1);
}
}
}
if (dp[n][amt] != max) {
return @intCast(dp[n][amt]);
} else {
return -1;
}
}
// Coin change: space-optimized dynamic programming
fn coinChangeDPComp(comptime coins: []i32, comptime amt: usize) i32 {
comptime var n = coins.len;
comptime var max = amt + 1;
// Initialize the dp table
var dp = [_]i32{0} ** (amt + 1);
@memset(&dp, max);
dp[0] = 0;
// State transitions
for (1..n + 1) |i| {
for (1..amt + 1) |a| {
if (coins[i - 1] > @as(i32, @intCast(a))) {
// If the coin exceeds the target amount, do not choose coin i
dp[a] = dp[a];
} else {
// Take the smaller result of not choosing and choosing coin i
dp[a] = @min(dp[a], dp[a - @as(usize, @intCast(coins[i - 1]))] + 1);
}
}
}
if (dp[amt] != max) {
return @intCast(dp[amt]);
} else {
return -1;
}
}
// Driver code
pub fn main() !void {
comptime var coins = [_]i32{ 1, 2, 5 };
comptime var amt: usize = 4;
// Dynamic programming
var res = coinChangeDP(&coins, amt);
std.debug.print("Minimum number of coins needed for the target amount: {}\n", .{res});
// Space-optimized dynamic programming
res = coinChangeDPComp(&coins, amt);
std.debug.print("Minimum number of coins needed for the target amount: {}\n", .{res});
_ = try std.io.getStdIn().reader().readByte();
}

View File

@@ -0,0 +1,66 @@
// File: coin_change_ii.zig
// Created Time: 2023-07-15
// Author: codingonion (coderonion@gmail.com)
const std = @import("std");
// Coin change II: dynamic programming
fn coinChangeIIDP(comptime coins: []i32, comptime amt: usize) i32 {
comptime var n = coins.len;
// Initialize the dp table
var dp = [_][amt + 1]i32{[_]i32{0} ** (amt + 1)} ** (n + 1);
// Initialize the first column
for (0..n + 1) |i| {
dp[i][0] = 1;
}
// State transitions
for (1..n + 1) |i| {
for (1..amt + 1) |a| {
if (coins[i - 1] > @as(i32, @intCast(a))) {
// If the coin exceeds the target amount, do not choose coin i
dp[i][a] = dp[i - 1][a];
} else {
// Add the counts for excluding coin i and including coin i
dp[i][a] = dp[i - 1][a] + dp[i][a - @as(usize, @intCast(coins[i - 1]))];
}
}
}
return dp[n][amt];
}
// Coin change II: space-optimized dynamic programming
fn coinChangeIIDPComp(comptime coins: []i32, comptime amt: usize) i32 {
comptime var n = coins.len;
// Initialize the dp table
var dp = [_]i32{0} ** (amt + 1);
dp[0] = 1;
// State transitions
for (1..n + 1) |i| {
for (1..amt + 1) |a| {
if (coins[i - 1] > @as(i32, @intCast(a))) {
// If the coin exceeds the target amount, do not choose coin i
dp[a] = dp[a];
} else {
// Add the counts for excluding coin i and including coin i
dp[a] = dp[a] + dp[a - @as(usize, @intCast(coins[i - 1]))];
}
}
}
return dp[amt];
}
// Driver code
pub fn main() !void {
comptime var coins = [_]i32{ 1, 2, 5 };
comptime var amt: usize = 5;
// Dynamic programming
var res = coinChangeIIDP(&coins, amt);
std.debug.print("Number of coin combinations for the target amount: {}\n", .{res});
// Space-optimized dynamic programming
res = coinChangeIIDPComp(&coins, amt);
std.debug.print("Number of coin combinations for the target amount: {}\n", .{res});
_ = try std.io.getStdIn().reader().readByte();
}

View File

@@ -0,0 +1,146 @@
// File: edit_distance.zig
// Created Time: 2023-07-15
// Author: codingonion (coderonion@gmail.com)
const std = @import("std");
// Edit distance: brute-force search
fn editDistanceDFS(comptime s: []const u8, comptime t: []const u8, i: usize, j: usize) i32 {
// If both prefixes s[0..i] and t[0..j] are empty, return 0
if (i == 0 and j == 0) {
return 0;
}
// If the prefix s[0..i] is empty, return the length j of the other prefix
if (i == 0) {
return @intCast(j);
}
// If the prefix t[0..j] is empty, return the length i of the other prefix
if (j == 0) {
return @intCast(i);
}
// 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 edits = the minimum among the insertion, deletion, and replacement subproblems + 1
var insert = editDistanceDFS(s, t, i, j - 1);
var delete = editDistanceDFS(s, t, i - 1, j);
var replace = editDistanceDFS(s, t, i - 1, j - 1);
// Return the minimum number of edits
return @min(@min(insert, delete), replace) + 1;
}
// Edit distance: memoized search
fn editDistanceDFSMem(comptime s: []const u8, comptime t: []const u8, mem: anytype, i: usize, j: usize) i32 {
// If both prefixes s[0..i] and t[0..j] are empty, return 0
if (i == 0 and j == 0) {
return 0;
}
// If the prefix s[0..i] is empty, return the length j of the other prefix
if (i == 0) {
return @intCast(j);
}
// If the prefix t[0..j] is empty, return the length i of the other prefix
if (j == 0) {
return @intCast(i);
}
// If a result has already been recorded, return it directly
if (mem[i][j] != -1) {
return mem[i][j];
}
// 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 edits = the minimum among the insertion, deletion, and replacement subproblems + 1
var insert = editDistanceDFSMem(s, t, mem, i, j - 1);
var delete = editDistanceDFSMem(s, t, mem, i - 1, j);
var replace = editDistanceDFSMem(s, t, mem, i - 1, j - 1);
// Record and return the minimum number of edits
mem[i][j] = @min(@min(insert, delete), replace) + 1;
return mem[i][j];
}
// Edit distance: dynamic programming
fn editDistanceDP(comptime s: []const u8, comptime t: []const u8) i32 {
comptime var n = s.len;
comptime var m = t.len;
var dp = [_][m + 1]i32{[_]i32{0} ** (m + 1)} ** (n + 1);
// State transitions: first row and first column
for (1..n + 1) |i| {
dp[i][0] = @intCast(i);
}
for (1..m + 1) |j| {
dp[0][j] = @intCast(j);
}
// State transitions: remaining rows and columns
for (1..n + 1) |i| {
for (1..m + 1) |j| {
if (s[i - 1] == t[j - 1]) {
// If the two characters are equal, skip both of them
dp[i][j] = dp[i - 1][j - 1];
} else {
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
dp[i][j] = @min(@min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
}
}
}
return dp[n][m];
}
// Edit distance: space-optimized dynamic programming
fn editDistanceDPComp(comptime s: []const u8, comptime t: []const u8) i32 {
comptime var n = s.len;
comptime var m = t.len;
var dp = [_]i32{0} ** (m + 1);
// State transitions: first row
for (1..m + 1) |j| {
dp[j] = @intCast(j);
}
// State transitions: remaining rows
for (1..n + 1) |i| {
// State transitions: first column
var leftup = dp[0]; // Temporarily store dp[i-1, j-1]
dp[0] = @intCast(i);
// State transitions: remaining columns
for (1..m + 1) |j| {
var temp = dp[j];
if (s[i - 1] == t[j - 1]) {
// If the two characters are equal, skip both of them
dp[j] = leftup;
} else {
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
dp[j] = @min(@min(dp[j - 1], dp[j]), leftup) + 1;
}
leftup = temp; // Update to dp[i-1, j-1] for the next iteration
}
}
return dp[m];
}
// Driver code
pub fn main() !void {
const s = "bag";
const t = "pack";
comptime var n = s.len;
comptime var m = t.len;
// Brute-force search
var res = editDistanceDFS(s, t, n, m);
std.debug.print("Changing {s} to {s} requires at least {} edits\n", .{ s, t, res });
// Memoized search
var mem = [_][m + 1]i32{[_]i32{-1} ** (m + 1)} ** (n + 1);
res = editDistanceDFSMem(s, t, @constCast(&mem), n, m);
std.debug.print("Changing {s} to {s} requires at least {} edits\n", .{ s, t, res });
// Dynamic programming
res = editDistanceDP(s, t);
std.debug.print("Changing {s} to {s} requires at least {} edits\n", .{ s, t, res });
// Space-optimized dynamic programming
res = editDistanceDPComp(s, t);
std.debug.print("Changing {s} to {s} requires at least {} edits\n", .{ s, t, res });
_ = try std.io.getStdIn().reader().readByte();
}

View File

@@ -0,0 +1,110 @@
// File: knapsack.zig
// Created Time: 2023-07-15
// Author: codingonion (coderonion@gmail.com)
const std = @import("std");
// 0-1 knapsack: brute-force search
fn knapsackDFS(wgt: []i32, val: []i32, i: usize, c: usize) i32 {
// If all items have been considered or no capacity remains, return value 0
if (i == 0 or c == 0) {
return 0;
}
// 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 values obtained by excluding and including item i
var no = knapsackDFS(wgt, val, i - 1, c);
var yes = knapsackDFS(wgt, val, i - 1, c - @as(usize, @intCast(wgt[i - 1]))) + val[i - 1];
// Return the larger value from the two choices
return @max(no, yes);
}
// 0-1 knapsack: memoized search
fn knapsackDFSMem(wgt: []i32, val: []i32, mem: anytype, i: usize, c: usize) i32 {
// If all items have been considered or no capacity remains, return value 0
if (i == 0 or c == 0) {
return 0;
}
// If a result has already been recorded, return it directly
if (mem[i][c] != -1) {
return mem[i][c];
}
// 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 values obtained by excluding and including item i
var no = knapsackDFSMem(wgt, val, mem, i - 1, c);
var yes = knapsackDFSMem(wgt, val, mem, i - 1, c - @as(usize, @intCast(wgt[i - 1]))) + val[i - 1];
// Record and return the larger value from the two choices
mem[i][c] = @max(no, yes);
return mem[i][c];
}
// 0-1 knapsack: dynamic programming
fn knapsackDP(comptime wgt: []i32, val: []i32, comptime cap: usize) i32 {
comptime var n = wgt.len;
// Initialize the dp table
var dp = [_][cap + 1]i32{[_]i32{0} ** (cap + 1)} ** (n + 1);
// State transitions
for (1..n + 1) |i| {
for (1..cap + 1) |c| {
if (wgt[i - 1] > c) {
// If item i exceeds the remaining capacity, do not choose it
dp[i][c] = dp[i - 1][c];
} else {
// Take the larger value obtained by excluding and including item i
dp[i][c] = @max(dp[i - 1][c], dp[i - 1][c - @as(usize, @intCast(wgt[i - 1]))] + val[i - 1]);
}
}
}
return dp[n][cap];
}
// 0-1 knapsack: space-optimized dynamic programming
fn knapsackDPComp(wgt: []i32, val: []i32, comptime cap: usize) i32 {
var n = wgt.len;
// Initialize the dp table
var dp = [_]i32{0} ** (cap + 1);
// State transitions
for (1..n + 1) |i| {
// Traverse in decreasing order
var c = cap;
while (c > 0) : (c -= 1) {
if (wgt[i - 1] < c) {
// Take the larger value obtained by excluding and including item i
dp[c] = @max(dp[c], dp[c - @as(usize, @intCast(wgt[i - 1]))] + val[i - 1]);
}
}
}
return dp[cap];
}
// Driver code
pub fn main() !void {
comptime var wgt = [_]i32{ 10, 20, 30, 40, 50 };
comptime var val = [_]i32{ 50, 120, 150, 210, 240 };
comptime var cap = 50;
comptime var n = wgt.len;
// Brute-force search
var res = knapsackDFS(&wgt, &val, n, cap);
std.debug.print("Maximum total item value within the knapsack capacity: {}\n", .{res});
// Memoized search
var mem = [_][cap + 1]i32{[_]i32{-1} ** (cap + 1)} ** (n + 1);
res = knapsackDFSMem(&wgt, &val, @constCast(&mem), n, cap);
std.debug.print("Maximum total item value within the knapsack capacity: {}\n", .{res});
// Dynamic programming
res = knapsackDP(&wgt, &val, cap);
std.debug.print("Maximum total item value within the knapsack capacity: {}\n", .{res});
// Space-optimized dynamic programming
res = knapsackDPComp(&wgt, &val, cap);
std.debug.print("Maximum total item value within the knapsack capacity: {}\n", .{res});
_ = try std.io.getStdIn().reader().readByte();
}

View File

@@ -0,0 +1,54 @@
// File: min_cost_climbing_stairs_dp.zig
// Created Time: 2023-07-15
// Author: codingonion (coderonion@gmail.com)
const std = @import("std");
// Minimum cost to climb stairs: dynamic programming
fn minCostClimbingStairsDP(comptime cost: []i32) i32 {
comptime var n = cost.len - 1;
if (n == 1 or n == 2) {
return cost[n];
}
// Initialize the dp table to store subproblem solutions
var dp = [_]i32{-1} ** (n + 1);
// Initial states: set the solutions to the smallest subproblems
dp[1] = cost[1];
dp[2] = cost[2];
// State transitions: solve progressively larger subproblems using smaller ones
for (3..n + 1) |i| {
dp[i] = @min(dp[i - 1], dp[i - 2]) + cost[i];
}
return dp[n];
}
// Minimum cost to climb stairs: space-optimized dynamic programming
fn minCostClimbingStairsDPComp(cost: []i32) i32 {
var n = cost.len - 1;
if (n == 1 or n == 2) {
return cost[n];
}
var a = cost[1];
var b = cost[2];
// State transitions: solve progressively larger subproblems using smaller ones
for (3..n + 1) |i| {
var tmp = b;
b = @min(a, tmp) + cost[i];
a = tmp;
}
return b;
}
// Driver code
pub fn main() !void {
comptime var cost = [_]i32{ 0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1 };
std.debug.print("Input stair costs: {any}\n", .{cost});
var res = minCostClimbingStairsDP(&cost);
std.debug.print("Minimum cost to climb the stairs: {}\n", .{res});
res = minCostClimbingStairsDPComp(&cost);
std.debug.print("Minimum cost to climb the stairs: {}\n", .{res});
_ = try std.io.getStdIn().reader().readByte();
}

View File

@@ -0,0 +1,122 @@
// File: min_path_sum.zig
// Created Time: 2023-07-15
// Author: codingonion (coderonion@gmail.com)
const std = @import("std");
// Minimum path sum: brute-force search
fn minPathSumDFS(grid: anytype, i: i32, j: i32) i32 {
// Stop searching at the top-left cell
if (i == 0 and j == 0) {
return grid[0][0];
}
// If a row or column index is out of bounds, use the maximum i32 value to represent infinite cost
if (i < 0 or j < 0) {
return std.math.maxInt(i32);
}
// Calculate the minimum path costs from the top-left corner to (i-1, j) and (i, j-1)
var up = minPathSumDFS(grid, i - 1, j);
var left = minPathSumDFS(grid, i, j - 1);
// Return the minimum path cost from the top-left corner to (i, j)
return @min(left, up) + grid[@as(usize, @intCast(i))][@as(usize, @intCast(j))];
}
// Minimum path sum: memoized search
fn minPathSumDFSMem(grid: anytype, mem: anytype, i: i32, j: i32) i32 {
// Stop searching at the top-left cell
if (i == 0 and j == 0) {
return grid[0][0];
}
// If a row or column index is out of bounds, use the maximum i32 value to represent infinite cost
if (i < 0 or j < 0) {
return std.math.maxInt(i32);
}
// If a result has already been recorded, return it directly
if (mem[@as(usize, @intCast(i))][@as(usize, @intCast(j))] != -1) {
return mem[@as(usize, @intCast(i))][@as(usize, @intCast(j))];
}
// Calculate the minimum path costs from the top-left corner to (i-1, j) and (i, j-1)
var up = minPathSumDFSMem(grid, mem, i - 1, j);
var left = minPathSumDFSMem(grid, mem, i, j - 1);
// Return the minimum path cost from the top-left corner to (i, j)
// Record and return the minimum path cost from the top-left corner to (i, j)
mem[@as(usize, @intCast(i))][@as(usize, @intCast(j))] = @min(left, up) + grid[@as(usize, @intCast(i))][@as(usize, @intCast(j))];
return mem[@as(usize, @intCast(i))][@as(usize, @intCast(j))];
}
// Minimum path sum: dynamic programming
fn minPathSumDP(comptime grid: anytype) i32 {
comptime var n = grid.len;
comptime var m = grid[0].len;
// Initialize the dp table
var dp = [_][m]i32{[_]i32{0} ** m} ** n;
dp[0][0] = grid[0][0];
// State transitions: first row
for (1..m) |j| {
dp[0][j] = dp[0][j - 1] + grid[0][j];
}
// State transitions: first column
for (1..n) |i| {
dp[i][0] = dp[i - 1][0] + grid[i][0];
}
// State transitions: remaining rows and columns
for (1..n) |i| {
for (1..m) |j| {
dp[i][j] = @min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
}
}
return dp[n - 1][m - 1];
}
// Minimum path sum: space-optimized dynamic programming
fn minPathSumDPComp(comptime grid: anytype) i32 {
comptime var n = grid.len;
comptime var m = grid[0].len;
// Initialize the dp table
var dp = [_]i32{0} ** m;
// State transitions: first row
dp[0] = grid[0][0];
for (1..m) |j| {
dp[j] = dp[j - 1] + grid[0][j];
}
// State transitions: remaining rows
for (1..n) |i| {
// State transitions: first column
dp[0] = dp[0] + grid[i][0];
for (1..m) |j| {
dp[j] = @min(dp[j - 1], dp[j]) + grid[i][j];
}
}
return dp[m - 1];
}
// Driver code
pub fn main() !void {
comptime var grid = [_][4]i32{
[_]i32{ 1, 3, 1, 5 },
[_]i32{ 2, 2, 4, 2 },
[_]i32{ 5, 3, 2, 1 },
[_]i32{ 4, 3, 5, 2 },
};
comptime var n = grid.len;
comptime var m = grid[0].len;
// Brute-force search
var res = minPathSumDFS(&grid, n - 1, m - 1);
std.debug.print("Minimum path sum from the top-left to the bottom-right corner: {}\n", .{res});
// Memoized search
var mem = [_][m]i32{[_]i32{-1} ** m} ** n;
res = minPathSumDFSMem(&grid, &mem, n - 1, m - 1);
std.debug.print("Minimum path sum from the top-left to the bottom-right corner: {}\n", .{res});
// Dynamic programming
res = minPathSumDP(&grid);
std.debug.print("Minimum path sum from the top-left to the bottom-right corner: {}\n", .{res});
// Space-optimized dynamic programming
res = minPathSumDPComp(&grid);
std.debug.print("Minimum path sum from the top-left to the bottom-right corner: {}\n", .{res});
_ = try std.io.getStdIn().reader().readByte();
}

View File

@@ -0,0 +1,62 @@
// File: unbounded_knapsack.zig
// Created Time: 2023-07-15
// Author: codingonion (coderonion@gmail.com)
const std = @import("std");
// Unbounded knapsack: dynamic programming
fn unboundedKnapsackDP(comptime wgt: []i32, val: []i32, comptime cap: usize) i32 {
comptime var n = wgt.len;
// Initialize the dp table
var dp = [_][cap + 1]i32{[_]i32{0} ** (cap + 1)} ** (n + 1);
// State transitions
for (1..n + 1) |i| {
for (1..cap + 1) |c| {
if (wgt[i - 1] > c) {
// If item i exceeds the remaining capacity, do not choose it
dp[i][c] = dp[i - 1][c];
} else {
// Take the larger value obtained by excluding and including item i
dp[i][c] = @max(dp[i - 1][c], dp[i][c - @as(usize, @intCast(wgt[i - 1]))] + val[i - 1]);
}
}
}
return dp[n][cap];
}
// Unbounded knapsack: space-optimized dynamic programming
fn unboundedKnapsackDPComp(comptime wgt: []i32, val: []i32, comptime cap: usize) i32 {
comptime var n = wgt.len;
// Initialize the dp table
var dp = [_]i32{0} ** (cap + 1);
// State transitions
for (1..n + 1) |i| {
for (1..cap + 1) |c| {
if (wgt[i - 1] > c) {
// If item i exceeds the remaining capacity, do not choose it
dp[c] = dp[c];
} else {
// Take the larger value obtained by excluding and including item i
dp[c] = @max(dp[c], dp[c - @as(usize, @intCast(wgt[i - 1]))] + val[i - 1]);
}
}
}
return dp[cap];
}
// Driver code
pub fn main() !void {
comptime var wgt = [_]i32{ 1, 2, 3 };
comptime var val = [_]i32{ 5, 11, 15 };
comptime var cap = 4;
// Dynamic programming
var res = unboundedKnapsackDP(&wgt, &val, cap);
std.debug.print("Maximum total item value within the knapsack capacity: {}\n", .{res});
// Space-optimized dynamic programming
res = unboundedKnapsackDPComp(&wgt, &val, cap);
std.debug.print("Maximum total item value within the knapsack capacity: {}\n", .{res});
_ = try std.io.getStdIn().reader().readByte();
}