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

@@ -8,27 +8,27 @@
/* Backtracking */
void backtrack(int *choices, int state, int n, int *res, int len) {
// 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
for (int i = 0; i < len; i++) {
int choice = choices[i];
// 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, len);
// Backtrack
}
}
/* Climbing stairs: Backtracking */
/* Climbing stairs: backtracking */
int climbingStairsBacktrack(int n) {
int choices[2] = {1, 2}; // Can choose to climb up 1 or 2 stairs
int state = 0; // Start climbing from the 0-th stair
int choices[2] = {1, 2}; // Choose to climb 1 or 2 steps
int state = 0; // Start climbing from step 0
int *res = (int *)malloc(sizeof(int));
*res = 0; // Use res[0] to record the solution count
*res = 0; // Use res[0] to record the number of ways
int len = sizeof(choices) / sizeof(int);
backtrack(choices, state, n, res, len);
int result = *res;
@@ -36,12 +36,12 @@ int climbingStairsBacktrack(int n) {
return result;
}
/* Driver Code */
/* Driver code */
int main() {
int n = 9;
int res = climbingStairsBacktrack(n);
printf("Climbing %d stairs has %d solutions\n", n, res);
printf("Number of ways to climb %d stairs: %d\n", n, res);
return 0;
}

View File

@@ -6,22 +6,22 @@
#include "../utils/common.h"
/* 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 = malloc((n + 1) * sizeof(int *));
for (int i = 0; i <= n; i++) {
dp[i] = calloc(3, sizeof(int));
}
// 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];
@@ -35,12 +35,12 @@ int climbingStairsConstraintDP(int n) {
return res;
}
/* Driver Code */
/* Driver code */
int main() {
int n = 9;
int res = climbingStairsConstraintDP(n);
printf("Climbing %d stairs has %d solutions\n", n, res);
printf("Number of ways to climb %d stairs: %d\n", n, res);
return 0;
}

View File

@@ -8,7 +8,7 @@
/* 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]
@@ -16,17 +16,17 @@ int dfs(int i) {
return count;
}
/* Climbing stairs: Search */
/* Climbing stairs: search */
int climbingStairsDFS(int n) {
return dfs(n);
}
/* Driver Code */
/* Driver code */
int main() {
int n = 9;
int res = climbingStairsDFS(n);
printf("Climbing %d stairs has %d solutions\n", n, res);
printf("Number of ways to climb %d stairs: %d\n", n, res);
return 0;
}

View File

@@ -6,12 +6,12 @@
#include "../utils/common.h"
/* 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]
@@ -21,9 +21,9 @@ int dfs(int i, int *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 = (int *)malloc((n + 1) * sizeof(int));
for (int i = 0; i <= n; i++) {
mem[i] = -1;
@@ -33,12 +33,12 @@ int climbingStairsDFSMem(int n) {
return result;
}
/* Driver Code */
/* Driver code */
int main() {
int n = 9;
int res = climbingStairsDFSMem(n);
printf("Climbing %d stairs has %d solutions\n", n, res);
printf("Number of ways to climb %d stairs: %d\n", n, res);
return 0;
}

View File

@@ -6,16 +6,16 @@
#include "../utils/common.h"
/* 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 = (int *)malloc((n + 1) * sizeof(int));
// 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];
}
@@ -24,7 +24,7 @@ int climbingStairsDP(int n) {
return result;
}
/* Climbing stairs: Space-optimized dynamic programming */
/* Climbing stairs: space-optimized dynamic programming */
int climbingStairsDPComp(int n) {
if (n == 1 || n == 2)
return n;
@@ -37,15 +37,15 @@ int climbingStairsDPComp(int n) {
return b;
}
/* Driver Code */
/* Driver code */
int main() {
int n = 9;
int res = climbingStairsDP(n);
printf("Climbing %d stairs has %d solutions\n", n, res);
printf("Number of ways to climb %d stairs: %d\n", n, res);
res = climbingStairsDPComp(n);
printf("Climbing %d stairs has %d solutions\n", n, res);
printf("Number of ways to climb %d stairs: %d\n", n, res);
return 0;
}

View File

@@ -6,32 +6,32 @@
#include "../utils/common.h"
/* Find minimum value */
/* Find the minimum */
int myMin(int a, int b) {
return a < b ? a : b;
}
/* Coin change: Dynamic programming */
/* Coin change: dynamic programming */
int coinChangeDP(int coins[], int amt, int coinsSize) {
int n = coinsSize;
int MAX = amt + 1;
// Initialize dp table
// Initialize the dp table
int **dp = malloc((n + 1) * sizeof(int *));
for (int i = 0; i <= n; i++) {
dp[i] = calloc(amt + 1, sizeof(int));
}
// 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] = myMin(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1);
}
}
@@ -45,25 +45,25 @@ int coinChangeDP(int coins[], int amt, int coinsSize) {
return res;
}
/* Coin change: Space-optimized dynamic programming */
/* Coin change: space-optimized dynamic programming */
int coinChangeDPComp(int coins[], int amt, int coinsSize) {
int n = coinsSize;
int MAX = amt + 1;
// Initialize dp table
// Initialize the dp table
int *dp = malloc((amt + 1) * sizeof(int));
for (int j = 1; j <= amt; j++) {
dp[j] = 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] = myMin(dp[a], dp[a - coins[i - 1]] + 1);
}
}
@@ -82,11 +82,11 @@ int main() {
// Dynamic programming
int res = coinChangeDP(coins, amt, coinsSize);
printf("Minimum number of coins needed to make target amount is %d\n", res);
printf("Minimum number of coins needed to make the target amount: %d\n", res);
// Space-optimized dynamic programming
res = coinChangeDPComp(coins, amt, coinsSize);
printf("Minimum number of coins needed to make target amount is %d\n", res);
printf("Minimum number of coins needed to make the target amount: %d\n", res);
return 0;
}

View File

@@ -6,26 +6,26 @@
#include "../utils/common.h"
/* Coin change II: Dynamic programming */
/* Coin change II: dynamic programming */
int coinChangeIIDP(int coins[], int amt, int coinsSize) {
int n = coinsSize;
// Initialize dp table
// Initialize the dp table
int **dp = malloc((n + 1) * sizeof(int *));
for (int i = 0; i <= n; i++) {
dp[i] = calloc(amt + 1, sizeof(int));
}
// 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]];
}
}
@@ -39,20 +39,20 @@ int coinChangeIIDP(int coins[], int amt, int coinsSize) {
return res;
}
/* Coin change II: Space-optimized dynamic programming */
/* Coin change II: space-optimized dynamic programming */
int coinChangeIIDPComp(int coins[], int amt, int coinsSize) {
int n = coinsSize;
// Initialize dp table
// Initialize the dp table
int *dp = calloc(amt + 1, sizeof(int));
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]];
}
}
@@ -71,11 +71,11 @@ int main() {
// Dynamic programming
int res = coinChangeIIDP(coins, amt, coinsSize);
printf("Number of coin combinations to make target amount is %d\n", res);
printf("Number of coin combinations that make the target amount: %d\n", res);
// Space-optimized dynamic programming
res = coinChangeIIDPComp(coins, amt, coinsSize);
printf("Number of coin combinations to make target amount is %d\n", res);
printf("Number of coin combinations that make the target amount: %d\n", res);
return 0;
}

View File

@@ -6,80 +6,80 @@
#include "../utils/common.h"
/* Find minimum value */
/* Find the minimum */
int myMin(int a, int b) {
return a < b ? a : b;
}
/* Edit distance: Brute-force search */
/* Edit distance: brute-force search */
int editDistanceDFS(char *s, char *t, int i, int j) {
// If both s and t are empty, return 0
// If both prefixes s[0:i] and t[0:j] are empty, return 0
if (i == 0 && j == 0)
return 0;
// If s is empty, return length of t
// If the prefix s[0:i] is empty, return j, the length of t[0:j]
if (i == 0)
return j;
// If t is empty, return length of s
// If the prefix t[0:j] is empty, return i, the length of s[0:i]
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 del = 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 myMin(myMin(insert, del), replace) + 1;
}
/* Edit distance: Memoization search */
/* Edit distance: memoized search */
int editDistanceDFSMem(char *s, char *t, int memCols, int **mem, int i, int j) {
// If both s and t are empty, return 0
// If both prefixes s[0:i] and t[0:j] are empty, return 0
if (i == 0 && j == 0)
return 0;
// If s is empty, return length of t
// If the prefix s[0:i] is empty, return j, the length of t[0:j]
if (i == 0)
return j;
// If t is empty, return length of s
// If the prefix t[0:j] is empty, return i, the length of s[0:i]
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, memCols, 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, memCols, mem, i, j - 1);
int del = editDistanceDFSMem(s, t, memCols, mem, i - 1, j);
int replace = editDistanceDFSMem(s, t, memCols, mem, i - 1, j - 1);
// Record and return minimum edit steps
// Record and return the minimum number of edits
mem[i][j] = myMin(myMin(insert, del), replace) + 1;
return mem[i][j];
}
/* Edit distance: Dynamic programming */
/* Edit distance: dynamic programming */
int editDistanceDP(char *s, char *t, int n, int m) {
int **dp = malloc((n + 1) * sizeof(int *));
for (int i = 0; i <= n; i++) {
dp[i] = calloc(m + 1, sizeof(int));
}
// 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] = myMin(myMin(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
}
}
@@ -92,29 +92,29 @@ int editDistanceDP(char *s, char *t, int n, int m) {
return res;
}
/* Edit distance: Space-optimized dynamic programming */
/* Edit distance: space-optimized dynamic programming */
int editDistanceDPComp(char *s, char *t, int n, int m) {
int *dp = calloc(m + 1, sizeof(int));
// 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] = myMin(myMin(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
}
}
int res = dp[m];
@@ -123,7 +123,7 @@ int editDistanceDPComp(char *s, char *t, int n, int m) {
return res;
}
/* Driver Code */
/* Driver code */
int main() {
char *s = "bag";
char *t = "pack";
@@ -131,16 +131,16 @@ int main() {
// Brute-force search
int res = editDistanceDFS(s, t, n, m);
printf("Changing %s to %s requires a minimum of %d edits\n", s, t, res);
printf("Changing %s to %s requires at least %d edits\n", s, t, res);
// Memoization search
// Memoized search
int **mem = malloc((n + 1) * sizeof(int *));
for (int i = 0; i <= n; i++) {
mem[i] = malloc((m + 1) * sizeof(int));
memset(mem[i], -1, (m + 1) * sizeof(int));
}
res = editDistanceDFSMem(s, t, m + 1, mem, n, m);
printf("Changing %s to %s requires a minimum of %d edits\n", s, t, res);
printf("Changing %s to %s requires at least %d edits\n", s, t, res);
// Free memory
for (int i = 0; i <= n; i++) {
free(mem[i]);
@@ -149,11 +149,11 @@ int main() {
// Dynamic programming
res = editDistanceDP(s, t, n, m);
printf("Changing %s to %s requires a minimum of %d edits\n", s, t, res);
printf("Changing %s to %s requires at least %d edits\n", s, t, res);
// Space-optimized dynamic programming
res = editDistanceDPComp(s, t, n, m);
printf("Changing %s to %s requires a minimum of %d edits\n", s, t, res);
printf("Changing %s to %s requires at least %d edits\n", s, t, res);
return 0;
}

View File

@@ -6,66 +6,66 @@
#include "../utils/common.h"
/* Find maximum value */
/* Find the maximum */
int myMax(int a, int b) {
return a > b ? a : b;
}
/* 0-1 knapsack: Brute-force search */
/* 0-1 knapsack: brute-force search */
int knapsackDFS(int wgt[], int val[], int i, int c) {
// If all items have been selected or knapsack has no remaining capacity, return value 0
// If all items have been considered or no capacity remains, return value 0
if (i == 0 || c == 0) {
return 0;
}
// If exceeds knapsack capacity, can only choose not to put it in
// If the item exceeds the remaining capacity, it must be excluded
if (wgt[i - 1] > c) {
return knapsackDFS(wgt, val, i - 1, c);
}
// Calculate the maximum value of not putting in and putting in item i
// Calculate the maximum values obtained by excluding and including item i
int no = knapsackDFS(wgt, val, i - 1, c);
int yes = knapsackDFS(wgt, val, i - 1, c - wgt[i - 1]) + val[i - 1];
// Return the larger value of the two options
// Return the larger value from the two choices
return myMax(no, yes);
}
/* 0-1 knapsack: Memoization search */
/* 0-1 knapsack: memoized search */
int knapsackDFSMem(int wgt[], int val[], int memCols, int **mem, int i, int c) {
// If all items have been selected or knapsack has no remaining capacity, return value 0
// If all items have been considered or no capacity remains, return value 0
if (i == 0 || c == 0) {
return 0;
}
// If there's a record, return it directly
// If a result has already been recorded, return it directly
if (mem[i][c] != -1) {
return mem[i][c];
}
// If exceeds knapsack capacity, can only choose not to put it in
// If the item exceeds the remaining capacity, it must be excluded
if (wgt[i - 1] > c) {
return knapsackDFSMem(wgt, val, memCols, mem, i - 1, c);
}
// Calculate the maximum value of not putting in and putting in item i
// Calculate the maximum values obtained by excluding and including item i
int no = knapsackDFSMem(wgt, val, memCols, mem, i - 1, c);
int yes = knapsackDFSMem(wgt, val, memCols, mem, i - 1, c - wgt[i - 1]) + val[i - 1];
// Record and return the larger value of the two options
// Record and return the larger value from the two choices
mem[i][c] = myMax(no, yes);
return mem[i][c];
}
/* 0-1 knapsack: Dynamic programming */
/* 0-1 knapsack: dynamic programming */
int knapsackDP(int wgt[], int val[], int cap, int wgtSize) {
int n = wgtSize;
// Initialize dp table
// Initialize the dp table
int **dp = malloc((n + 1) * sizeof(int *));
for (int i = 0; i <= n; i++) {
dp[i] = calloc(cap + 1, sizeof(int));
}
// 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] = myMax(dp[i - 1][c], dp[i - 1][c - wgt[i - 1]] + val[i - 1]);
}
}
@@ -78,17 +78,17 @@ int knapsackDP(int wgt[], int val[], int cap, int wgtSize) {
return res;
}
/* 0-1 knapsack: Space-optimized dynamic programming */
/* 0-1 knapsack: space-optimized dynamic programming */
int knapsackDPComp(int wgt[], int val[], int cap, int wgtSize) {
int n = wgtSize;
// Initialize dp table
// Initialize the dp table
int *dp = calloc(cap + 1, sizeof(int));
// State transition
// State transitions
for (int i = 1; i <= n; i++) {
// Traverse in reverse order
// Traverse in decreasing order
for (int c = cap; c >= 1; c--) {
if (wgt[i - 1] <= c) {
// The larger value between not selecting and selecting item i
// Take the larger value obtained by excluding and including item i
dp[c] = myMax(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
}
}
@@ -99,7 +99,7 @@ int knapsackDPComp(int wgt[], int val[], int cap, int wgtSize) {
return res;
}
/* Driver Code */
/* Driver code */
int main() {
int wgt[] = {10, 20, 30, 40, 50};
int val[] = {50, 120, 150, 210, 240};
@@ -109,16 +109,16 @@ int main() {
// Brute-force search
int res = knapsackDFS(wgt, val, n, cap);
printf("Maximum item value not exceeding knapsack capacity is %d\n", res);
printf("Maximum item value within the knapsack capacity: %d\n", res);
// Memoization search
// Memoized search
int **mem = malloc((n + 1) * sizeof(int *));
for (int i = 0; i <= n; i++) {
mem[i] = malloc((cap + 1) * sizeof(int));
memset(mem[i], -1, (cap + 1) * sizeof(int));
}
res = knapsackDFSMem(wgt, val, cap + 1, mem, n, cap);
printf("Maximum item value not exceeding knapsack capacity is %d\n", res);
printf("Maximum item value within the knapsack capacity: %d\n", res);
// Free memory
for (int i = 0; i <= n; i++) {
free(mem[i]);
@@ -127,11 +127,11 @@ int main() {
// Dynamic programming
res = knapsackDP(wgt, val, cap, wgtSize);
printf("Maximum item value not exceeding knapsack capacity is %d\n", res);
printf("Maximum item value within the knapsack capacity: %d\n", res);
// Space-optimized dynamic programming
res = knapsackDPComp(wgt, val, cap, wgtSize);
printf("Maximum item value not exceeding knapsack capacity is %d\n", res);
printf("Maximum item value within the knapsack capacity: %d\n", res);
return 0;
}

View File

@@ -6,22 +6,22 @@
#include "../utils/common.h"
/* Find minimum value */
/* Find the minimum */
int myMin(int a, int b) {
return a < b ? a : b;
}
/* Minimum cost climbing stairs: Dynamic programming */
/* Minimum cost to climb stairs: dynamic programming */
int minCostClimbingStairsDP(int cost[], int costSize) {
int n = costSize - 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 = calloc(n + 1, sizeof(int));
// 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] = myMin(dp[i - 1], dp[i - 2]) + cost[i];
}
@@ -31,7 +31,7 @@ int minCostClimbingStairsDP(int cost[], int costSize) {
return res;
}
/* Minimum cost climbing stairs: Space-optimized dynamic programming */
/* Minimum cost to climb stairs: space-optimized dynamic programming */
int minCostClimbingStairsDPComp(int cost[], int costSize) {
int n = costSize - 1;
if (n == 1 || n == 2)
@@ -45,18 +45,18 @@ int minCostClimbingStairsDPComp(int cost[], int costSize) {
return b;
}
/* Driver Code */
/* Driver code */
int main() {
int cost[] = {0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1};
int costSize = sizeof(cost) / sizeof(cost[0]);
printf("Input stair cost list is:");
printf("Input list of stair costs:");
printArray(cost, costSize);
int res = minCostClimbingStairsDP(cost, costSize);
printf("Minimum cost to climb stairs is %d\n", res);
printf("Minimum cost to climb the stairs: %d\n", res);
res = minCostClimbingStairsDPComp(cost, costSize);
printf("Minimum cost to climb stairs is %d\n", res);
printf("Minimum cost to climb the stairs: %d\n", res);
return 0;
}

View File

@@ -6,70 +6,70 @@
#include "../utils/common.h"
// Assume max matrix rows and columns is 100
// Assume the matrix has at most 100 rows and 100 columns
#define MAX_SIZE 100
/* Find minimum value */
/* Find the minimum */
int myMin(int a, int b) {
return a < b ? a : b;
}
/* Minimum path sum: Brute-force search */
/* Minimum path sum: brute-force search */
int minPathSumDFS(int grid[MAX_SIZE][MAX_SIZE], 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_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)
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 myMin(left, up) != INT_MAX ? myMin(left, up) + grid[i][j] : INT_MAX;
}
/* Minimum path sum: Memoization search */
/* Minimum path sum: memoized search */
int minPathSumDFSMem(int grid[MAX_SIZE][MAX_SIZE], int mem[MAX_SIZE][MAX_SIZE], 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_MAX;
}
// 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] = myMin(left, up) != INT_MAX ? myMin(left, up) + grid[i][j] : INT_MAX;
return mem[i][j];
}
/* Minimum path sum: Dynamic programming */
/* Minimum path sum: dynamic programming */
int minPathSumDP(int grid[MAX_SIZE][MAX_SIZE], int n, int m) {
// Initialize dp table
// Initialize the dp table
int **dp = malloc(n * sizeof(int *));
for (int i = 0; i < n; i++) {
dp[i] = calloc(m, sizeof(int));
}
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] = myMin(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
@@ -83,20 +83,20 @@ int minPathSumDP(int grid[MAX_SIZE][MAX_SIZE], int n, int m) {
return res;
}
/* Minimum path sum: Space-optimized dynamic programming */
/* Minimum path sum: space-optimized dynamic programming */
int minPathSumDPComp(int grid[MAX_SIZE][MAX_SIZE], int n, int m) {
// Initialize dp table
// Initialize the dp table
int *dp = calloc(m, sizeof(int));
// State transition: first row
// State transitions: first row
dp[0] = grid[0][0];
for (int j = 1; j < m; j++) {
dp[j] = dp[j - 1] + grid[0][j];
}
// State transition: rest of the rows
// State transitions: remaining rows
for (int i = 1; i < n; i++) {
// State transition: first column
// State transitions: first column
dp[0] = dp[0] + grid[i][0];
// State transition: rest of the columns
// State transitions: remaining columns
for (int j = 1; j < m; j++) {
dp[j] = myMin(dp[j - 1], dp[j]) + grid[i][j];
}
@@ -107,28 +107,28 @@ int minPathSumDPComp(int grid[MAX_SIZE][MAX_SIZE], int n, int m) {
return res;
}
/* Driver Code */
/* Driver code */
int main() {
int grid[MAX_SIZE][MAX_SIZE] = {{1, 3, 1, 5}, {2, 2, 4, 2}, {5, 3, 2, 1}, {4, 3, 5, 2}};
int n = 4, m = 4; // Matrix capacity is MAX_SIZE * MAX_SIZE, valid rows and columns are n * m
int n = 4, m = 4; // The matrix capacity is MAX_SIZE * MAX_SIZE; the active region has n rows and m columns
// Brute-force search
int res = minPathSumDFS(grid, n - 1, m - 1);
printf("Minimum path sum from top-left to bottom-right is %d\n", res);
printf("Minimum path sum from the top-left to the bottom-right corner: %d\n", res);
// Memoization search
// Memoized search
int mem[MAX_SIZE][MAX_SIZE];
memset(mem, -1, sizeof(mem));
res = minPathSumDFSMem(grid, mem, n - 1, m - 1);
printf("Minimum path sum from top-left to bottom-right is %d\n", res);
printf("Minimum path sum from the top-left to the bottom-right corner: %d\n", res);
// Dynamic programming
res = minPathSumDP(grid, n, m);
printf("Minimum path sum from top-left to bottom-right is %d\n", res);
printf("Minimum path sum from the top-left to the bottom-right corner: %d\n", res);
// Space-optimized dynamic programming
res = minPathSumDPComp(grid, n, m);
printf("Minimum path sum from top-left to bottom-right is %d\n", res);
printf("Minimum path sum from the top-left to the bottom-right corner: %d\n", res);
return 0;
}

View File

@@ -6,27 +6,27 @@
#include "../utils/common.h"
/* Find maximum value */
/* Find the maximum */
int myMax(int a, int b) {
return a > b ? a : b;
}
/* Unbounded knapsack: Dynamic programming */
/* Unbounded knapsack: dynamic programming */
int unboundedKnapsackDP(int wgt[], int val[], int cap, int wgtSize) {
int n = wgtSize;
// Initialize dp table
// Initialize the dp table
int **dp = malloc((n + 1) * sizeof(int *));
for (int i = 0; i <= n; i++) {
dp[i] = calloc(cap + 1, sizeof(int));
}
// 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] = myMax(dp[i - 1][c], dp[i][c - wgt[i - 1]] + val[i - 1]);
}
}
@@ -39,19 +39,19 @@ int unboundedKnapsackDP(int wgt[], int val[], int cap, int wgtSize) {
return res;
}
/* Unbounded knapsack: Space-optimized dynamic programming */
/* Unbounded knapsack: space-optimized dynamic programming */
int unboundedKnapsackDPComp(int wgt[], int val[], int cap, int wgtSize) {
int n = wgtSize;
// Initialize dp table
// Initialize the dp table
int *dp = calloc(cap + 1, sizeof(int));
// 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] = myMax(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
}
}
@@ -71,11 +71,11 @@ int main() {
// Dynamic programming
int res = unboundedKnapsackDP(wgt, val, cap, wgtSize);
printf("Maximum item value not exceeding knapsack capacity is %d\n", res);
printf("Maximum item value within the knapsack capacity: %d\n", res);
// Space-optimized dynamic programming
res = unboundedKnapsackDPComp(wgt, val, cap, wgtSize);
printf("Maximum item value not exceeding knapsack capacity is %d\n", res);
printf("Maximum item value within the knapsack capacity: %d\n", res);
return 0;
}