mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-10 16:00:36 +08:00
Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
This commit is contained in:
@@ -6,29 +6,29 @@
|
||||
|
||||
/* Backtracking */
|
||||
function backtrack(choices, state, n, res) {
|
||||
// When climbing to the n-th stair, add 1 to the solution count
|
||||
// When step n is reached, increase the number of ways by 1
|
||||
if (state === n) res.set(0, res.get(0) + 1);
|
||||
// Traverse all choices
|
||||
// Iterate over all choices
|
||||
for (const choice of 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 */
|
||||
function climbingStairsBacktrack(n) {
|
||||
const choices = [1, 2]; // Can choose to climb up 1 or 2 stairs
|
||||
const state = 0; // Start climbing from the 0-th stair
|
||||
const choices = [1, 2]; // Choose to climb 1 or 2 steps
|
||||
const state = 0; // Start climbing from step 0
|
||||
const res = new Map();
|
||||
res.set(0, 0); // Use res[0] to record the solution count
|
||||
res.set(0, 0); // Store the number of ways at key 0 in res
|
||||
backtrack(choices, state, n, res);
|
||||
return res.get(0);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const n = 9;
|
||||
const res = climbingStairsBacktrack(n);
|
||||
console.log(`Climbing ${n} stairs has ${res} solutions`);
|
||||
console.log(`Number of ways to climb ${n} stairs: ${res}`);
|
||||
|
||||
@@ -4,19 +4,19 @@
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Climbing stairs with constraint: Dynamic programming */
|
||||
/* Climbing stairs with constraints: dynamic programming */
|
||||
function climbingStairsConstraintDP(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
|
||||
const dp = Array.from(new Array(n + 1), () => new Array(3));
|
||||
// Initial state: preset the solution to the smallest subproblem
|
||||
// Initial states: set the solutions to the smallest subproblems
|
||||
dp[1][1] = 1;
|
||||
dp[1][2] = 0;
|
||||
dp[2][1] = 0;
|
||||
dp[2][2] = 1;
|
||||
// State transition: gradually solve larger subproblems from smaller ones
|
||||
// State transitions: solve progressively larger subproblems using smaller ones
|
||||
for (let i = 3; i <= n; i++) {
|
||||
dp[i][1] = dp[i - 1][2];
|
||||
dp[i][2] = dp[i - 2][1] + dp[i - 2][2];
|
||||
@@ -24,7 +24,7 @@ function climbingStairsConstraintDP(n) {
|
||||
return dp[n][1] + dp[n][2];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const n = 9;
|
||||
const res = climbingStairsConstraintDP(n);
|
||||
console.log(`Climbing ${n} stairs has ${res} solutions`);
|
||||
console.log(`Number of ways to climb ${n} stairs: ${res}`);
|
||||
|
||||
@@ -6,19 +6,19 @@
|
||||
|
||||
/* Search */
|
||||
function dfs(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]
|
||||
const count = dfs(i - 1) + dfs(i - 2);
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Climbing stairs: Search */
|
||||
/* Climbing stairs: search */
|
||||
function climbingStairsDFS(n) {
|
||||
return dfs(n);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const n = 9;
|
||||
const res = climbingStairsDFS(n);
|
||||
console.log(`Climbing ${n} stairs has ${res} solutions`);
|
||||
console.log(`Number of ways to climb ${n} stairs: ${res}`);
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Memoization search */
|
||||
/* Memoized search */
|
||||
function dfs(i, 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]
|
||||
const count = dfs(i - 1, mem) + dfs(i - 2, mem);
|
||||
@@ -17,14 +17,14 @@ function dfs(i, mem) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Climbing stairs: Memoization search */
|
||||
/* Climbing stairs: memoized search */
|
||||
function climbingStairsDFSMem(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
|
||||
const mem = new Array(n + 1).fill(-1);
|
||||
return dfs(n, mem);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const n = 9;
|
||||
const res = climbingStairsDFSMem(n);
|
||||
console.log(`Climbing ${n} stairs has ${res} solutions`);
|
||||
console.log(`Number of ways to climb ${n} stairs: ${res}`);
|
||||
|
||||
@@ -4,22 +4,22 @@
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Climbing stairs: Dynamic programming */
|
||||
/* Climbing stairs: dynamic programming */
|
||||
function climbingStairsDP(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
|
||||
const dp = new Array(n + 1).fill(-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 (let i = 3; i <= n; i++) {
|
||||
dp[i] = dp[i - 1] + dp[i - 2];
|
||||
}
|
||||
return dp[n];
|
||||
}
|
||||
|
||||
/* Climbing stairs: Space-optimized dynamic programming */
|
||||
/* Climbing stairs: space-optimized dynamic programming */
|
||||
function climbingStairsDPComp(n) {
|
||||
if (n === 1 || n === 2) return n;
|
||||
let a = 1,
|
||||
@@ -32,9 +32,9 @@ function climbingStairsDPComp(n) {
|
||||
return b;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const n = 9;
|
||||
let res = climbingStairsDP(n);
|
||||
console.log(`Climbing ${n} stairs has ${res} solutions`);
|
||||
console.log(`Number of ways to climb ${n} stairs: ${res}`);
|
||||
res = climbingStairsDPComp(n);
|
||||
console.log(`Climbing ${n} stairs has ${res} solutions`);
|
||||
console.log(`Number of ways to climb ${n} stairs: ${res}`);
|
||||
|
||||
@@ -4,26 +4,26 @@
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Coin change: Dynamic programming */
|
||||
/* Coin change: dynamic programming */
|
||||
function coinChangeDP(coins, amt) {
|
||||
const n = coins.length;
|
||||
const MAX = amt + 1;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
const dp = Array.from({ length: n + 1 }, () =>
|
||||
Array.from({ length: amt + 1 }, () => 0)
|
||||
);
|
||||
// State transition: first row and first column
|
||||
// State transitions: first row and first column
|
||||
for (let a = 1; a <= amt; a++) {
|
||||
dp[0][a] = MAX;
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
// State transitions: remaining rows and columns
|
||||
for (let i = 1; i <= n; i++) {
|
||||
for (let a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// If exceeds target amount, don't select coin i
|
||||
// If the coin exceeds the target amount, do not choose coin i
|
||||
dp[i][a] = dp[i - 1][a];
|
||||
} else {
|
||||
// The smaller value between not selecting and selecting coin i
|
||||
// Take the smaller result of not choosing and choosing coin i
|
||||
dp[i][a] = Math.min(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1);
|
||||
}
|
||||
}
|
||||
@@ -31,21 +31,21 @@ function coinChangeDP(coins, amt) {
|
||||
return dp[n][amt] !== MAX ? dp[n][amt] : -1;
|
||||
}
|
||||
|
||||
/* Coin change: Space-optimized dynamic programming */
|
||||
/* Coin change: space-optimized dynamic programming */
|
||||
function coinChangeDPComp(coins, amt) {
|
||||
const n = coins.length;
|
||||
const MAX = amt + 1;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
const dp = Array.from({ length: amt + 1 }, () => MAX);
|
||||
dp[0] = 0;
|
||||
// State transition
|
||||
// State transitions
|
||||
for (let i = 1; i <= n; i++) {
|
||||
for (let a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// If exceeds target amount, don't select coin i
|
||||
// If the coin exceeds the target amount, do not choose coin i
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// The smaller value between not selecting and selecting coin i
|
||||
// Take the smaller result of not choosing and choosing coin i
|
||||
dp[a] = Math.min(dp[a], dp[a - coins[i - 1]] + 1);
|
||||
}
|
||||
}
|
||||
@@ -53,14 +53,14 @@ function coinChangeDPComp(coins, amt) {
|
||||
return dp[amt] !== MAX ? dp[amt] : -1;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const coins = [1, 2, 5];
|
||||
const amt = 4;
|
||||
|
||||
// Dynamic programming
|
||||
let res = coinChangeDP(coins, amt);
|
||||
console.log(`Minimum coins needed to make target amount is ${res}`);
|
||||
console.log(`Minimum number of coins needed to make the target amount: ${res}`);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = coinChangeDPComp(coins, amt);
|
||||
console.log(`Minimum coins needed to make target amount is ${res}`);
|
||||
console.log(`Minimum number of coins needed to make the target amount: ${res}`);
|
||||
|
||||
@@ -4,25 +4,25 @@
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Coin change II: Dynamic programming */
|
||||
/* Coin change II: dynamic programming */
|
||||
function coinChangeIIDP(coins, amt) {
|
||||
const n = coins.length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
const dp = Array.from({ length: n + 1 }, () =>
|
||||
Array.from({ length: amt + 1 }, () => 0)
|
||||
);
|
||||
// Initialize first column
|
||||
// Initialize the first column
|
||||
for (let i = 0; i <= n; i++) {
|
||||
dp[i][0] = 1;
|
||||
}
|
||||
// State transition
|
||||
// State transitions
|
||||
for (let i = 1; i <= n; i++) {
|
||||
for (let 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]];
|
||||
}
|
||||
}
|
||||
@@ -30,20 +30,20 @@ function coinChangeIIDP(coins, amt) {
|
||||
return dp[n][amt];
|
||||
}
|
||||
|
||||
/* Coin change II: Space-optimized dynamic programming */
|
||||
/* Coin change II: space-optimized dynamic programming */
|
||||
function coinChangeIIDPComp(coins, amt) {
|
||||
const n = coins.length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
const dp = Array.from({ length: amt + 1 }, () => 0);
|
||||
dp[0] = 1;
|
||||
// State transition
|
||||
// State transitions
|
||||
for (let i = 1; i <= n; i++) {
|
||||
for (let 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]];
|
||||
}
|
||||
}
|
||||
@@ -51,14 +51,14 @@ function coinChangeIIDPComp(coins, amt) {
|
||||
return dp[amt];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const coins = [1, 2, 5];
|
||||
const amt = 5;
|
||||
|
||||
// Dynamic programming
|
||||
let res = coinChangeIIDP(coins, amt);
|
||||
console.log(`Number of coin combinations to make target amount is ${res}`);
|
||||
console.log(`Number of coin combinations that make the target amount: ${res}`);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = coinChangeIIDPComp(coins, amt);
|
||||
console.log(`Number of coin combinations to make target amount is ${res}`);
|
||||
console.log(`Number of coin combinations that make the target amount: ${res}`);
|
||||
|
||||
@@ -4,76 +4,76 @@
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Edit distance: Brute-force search */
|
||||
/* Edit distance: brute-force search */
|
||||
function editDistanceDFS(s, t, i, j) {
|
||||
// If both s and t are empty, return 0
|
||||
// If the current prefixes of both s and t are empty, return 0
|
||||
if (i === 0 && j === 0) return 0;
|
||||
|
||||
// If s is empty, return length of t
|
||||
// If the current prefix of s is empty, return the current prefix length j of t
|
||||
if (i === 0) return j;
|
||||
|
||||
// If t is empty, return length of s
|
||||
// If the current prefix of t is empty, return the current prefix length i of s
|
||||
if (j === 0) return i;
|
||||
|
||||
// If two characters are equal, skip both characters
|
||||
// If the two characters are equal, skip both of them
|
||||
if (s.charAt(i - 1) === t.charAt(j - 1))
|
||||
return editDistanceDFS(s, t, i - 1, j - 1);
|
||||
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
|
||||
const insert = editDistanceDFS(s, t, i, j - 1);
|
||||
const del = editDistanceDFS(s, t, i - 1, j);
|
||||
const replace = editDistanceDFS(s, t, i - 1, j - 1);
|
||||
// Return minimum edit steps
|
||||
// Return the minimum number of edits
|
||||
return Math.min(insert, del, replace) + 1;
|
||||
}
|
||||
|
||||
/* Edit distance: Memoization search */
|
||||
/* Edit distance: memoized search */
|
||||
function editDistanceDFSMem(s, t, mem, i, j) {
|
||||
// If both s and t are empty, return 0
|
||||
// If the current prefixes of both s and t are empty, return 0
|
||||
if (i === 0 && j === 0) return 0;
|
||||
|
||||
// If s is empty, return length of t
|
||||
// If the current prefix of s is empty, return the current prefix length j of t
|
||||
if (i === 0) return j;
|
||||
|
||||
// If t is empty, return length of s
|
||||
// If the current prefix of t is empty, return the current prefix length i of s
|
||||
if (j === 0) return i;
|
||||
|
||||
// If there's a record, return it directly
|
||||
// If a result has already been recorded, return it directly
|
||||
if (mem[i][j] !== -1) return mem[i][j];
|
||||
|
||||
// If two characters are equal, skip both characters
|
||||
// If the two characters are equal, skip both of them
|
||||
if (s.charAt(i - 1) === t.charAt(j - 1))
|
||||
return editDistanceDFSMem(s, t, mem, i - 1, j - 1);
|
||||
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
|
||||
const insert = editDistanceDFSMem(s, t, mem, i, j - 1);
|
||||
const del = editDistanceDFSMem(s, t, mem, i - 1, j);
|
||||
const replace = editDistanceDFSMem(s, t, mem, i - 1, j - 1);
|
||||
// Record and return minimum edit steps
|
||||
// Record and return the minimum number of edits
|
||||
mem[i][j] = Math.min(insert, del, replace) + 1;
|
||||
return mem[i][j];
|
||||
}
|
||||
|
||||
/* Edit distance: Dynamic programming */
|
||||
/* Edit distance: dynamic programming */
|
||||
function editDistanceDP(s, t) {
|
||||
const n = s.length,
|
||||
m = t.length;
|
||||
const dp = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
|
||||
// State transition: first row and first column
|
||||
// State transitions: first row and first column
|
||||
for (let i = 1; i <= n; i++) {
|
||||
dp[i][0] = i;
|
||||
}
|
||||
for (let j = 1; j <= m; j++) {
|
||||
dp[0][j] = j;
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
// State transitions: remaining rows and columns
|
||||
for (let i = 1; i <= n; i++) {
|
||||
for (let j = 1; j <= m; j++) {
|
||||
if (s.charAt(i - 1) === t.charAt(j - 1)) {
|
||||
// If two characters are equal, skip both characters
|
||||
// If the two characters are equal, skip both of them
|
||||
dp[i][j] = dp[i - 1][j - 1];
|
||||
} else {
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
|
||||
dp[i][j] =
|
||||
Math.min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]) + 1;
|
||||
}
|
||||
@@ -82,31 +82,31 @@ function editDistanceDP(s, t) {
|
||||
return dp[n][m];
|
||||
}
|
||||
|
||||
/* Edit distance: Space-optimized dynamic programming */
|
||||
/* Edit distance: space-optimized dynamic programming */
|
||||
function editDistanceDPComp(s, t) {
|
||||
const n = s.length,
|
||||
m = t.length;
|
||||
const dp = new Array(m + 1).fill(0);
|
||||
// State transition: first row
|
||||
// State transitions: first row
|
||||
for (let j = 1; j <= m; j++) {
|
||||
dp[j] = j;
|
||||
}
|
||||
// State transition: rest of the rows
|
||||
// State transitions: remaining rows
|
||||
for (let i = 1; i <= n; i++) {
|
||||
// State transition: first column
|
||||
// State transitions: first column
|
||||
let leftup = dp[0]; // Temporarily store dp[i-1, j-1]
|
||||
dp[0] = i;
|
||||
// State transition: rest of the columns
|
||||
// State transitions: remaining columns
|
||||
for (let j = 1; j <= m; j++) {
|
||||
const temp = dp[j];
|
||||
if (s.charAt(i - 1) === t.charAt(j - 1)) {
|
||||
// If two characters are equal, skip both characters
|
||||
// If the two characters are equal, skip both of them
|
||||
dp[j] = leftup;
|
||||
} else {
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
|
||||
dp[j] = Math.min(dp[j - 1], dp[j], leftup) + 1;
|
||||
}
|
||||
leftup = temp; // Update for next round's dp[i-1, j-1]
|
||||
leftup = temp; // Update to dp[i-1, j-1] for the next iteration
|
||||
}
|
||||
}
|
||||
return dp[m];
|
||||
@@ -119,17 +119,17 @@ const n = s.length,
|
||||
|
||||
// Brute-force search
|
||||
let res = editDistanceDFS(s, t, n, m);
|
||||
console.log(`Changing ${s} to ${t} requires minimum ${res} edits`);
|
||||
console.log(`Minimum number of edits to transform ${s} into ${t}: ${res}`);
|
||||
|
||||
// Memoization search
|
||||
// Memoized search
|
||||
const mem = Array.from(new Array(n + 1), () => new Array(m + 1).fill(-1));
|
||||
res = editDistanceDFSMem(s, t, mem, n, m);
|
||||
console.log(`Changing ${s} to ${t} requires minimum ${res} edits`);
|
||||
console.log(`Minimum number of edits to transform ${s} into ${t}: ${res}`);
|
||||
|
||||
// Dynamic programming
|
||||
res = editDistanceDP(s, t);
|
||||
console.log(`Changing ${s} to ${t} requires minimum ${res} edits`);
|
||||
console.log(`Minimum number of edits to transform ${s} into ${t}: ${res}`);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = editDistanceDPComp(s, t);
|
||||
console.log(`Changing ${s} to ${t} requires minimum ${res} edits`);
|
||||
console.log(`Minimum number of edits to transform ${s} into ${t}: ${res}`);
|
||||
|
||||
@@ -4,61 +4,61 @@
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* 0-1 knapsack: Brute-force search */
|
||||
/* 0-1 knapsack: brute-force search */
|
||||
function knapsackDFS(wgt, val, i, 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
|
||||
const no = knapsackDFS(wgt, val, i - 1, c);
|
||||
const yes = knapsackDFS(wgt, val, i - 1, c - wgt[i - 1]) + val[i - 1];
|
||||
// Return the larger value of the two options
|
||||
// Return the larger value from the two choices
|
||||
return Math.max(no, yes);
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Memoization search */
|
||||
/* 0-1 knapsack: memoized search */
|
||||
function knapsackDFSMem(wgt, val, mem, i, c) {
|
||||
// If all items have been selected or knapsack has no remaining capacity, return value 0
|
||||
// If all items have been considered or no capacity remains, return value 0
|
||||
if (i === 0 || c === 0) {
|
||||
return 0;
|
||||
}
|
||||
// If there's a record, return it directly
|
||||
// If a result has already been recorded, return it directly
|
||||
if (mem[i][c] !== -1) {
|
||||
return mem[i][c];
|
||||
}
|
||||
// If exceeds knapsack capacity, can only choose not to put it in
|
||||
// If the item exceeds the remaining capacity, it must be excluded
|
||||
if (wgt[i - 1] > c) {
|
||||
return knapsackDFSMem(wgt, val, mem, i - 1, c);
|
||||
}
|
||||
// Calculate the maximum value of not putting in and putting in item i
|
||||
// Calculate the maximum values obtained by excluding and including item i
|
||||
const no = knapsackDFSMem(wgt, val, mem, i - 1, c);
|
||||
const yes =
|
||||
knapsackDFSMem(wgt, val, mem, i - 1, c - wgt[i - 1]) + val[i - 1];
|
||||
// Record and return the larger value of the two options
|
||||
// Record and return the larger value from the two choices
|
||||
mem[i][c] = Math.max(no, yes);
|
||||
return mem[i][c];
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Dynamic programming */
|
||||
/* 0-1 knapsack: dynamic programming */
|
||||
function knapsackDP(wgt, val, cap) {
|
||||
const n = wgt.length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
const dp = Array(n + 1)
|
||||
.fill(0)
|
||||
.map(() => Array(cap + 1).fill(0));
|
||||
// State transition
|
||||
// State transitions
|
||||
for (let i = 1; i <= n; i++) {
|
||||
for (let c = 1; c <= cap; c++) {
|
||||
if (wgt[i - 1] > c) {
|
||||
// If exceeds knapsack capacity, don't select item i
|
||||
// If item i exceeds the remaining capacity, do not choose it
|
||||
dp[i][c] = dp[i - 1][c];
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
dp[i][c] = Math.max(
|
||||
dp[i - 1][c],
|
||||
dp[i - 1][c - wgt[i - 1]] + val[i - 1]
|
||||
@@ -69,17 +69,17 @@ function knapsackDP(wgt, val, cap) {
|
||||
return dp[n][cap];
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Space-optimized dynamic programming */
|
||||
/* 0-1 knapsack: space-optimized dynamic programming */
|
||||
function knapsackDPComp(wgt, val, cap) {
|
||||
const n = wgt.length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
const dp = Array(cap + 1).fill(0);
|
||||
// State transition
|
||||
// State transitions
|
||||
for (let i = 1; i <= n; i++) {
|
||||
// Traverse in reverse order
|
||||
// Traverse in decreasing order
|
||||
for (let c = cap; c >= 1; c--) {
|
||||
if (wgt[i - 1] <= c) {
|
||||
// The larger value between not selecting and selecting item i
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
dp[c] = Math.max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
@@ -87,7 +87,7 @@ function knapsackDPComp(wgt, val, cap) {
|
||||
return dp[cap];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const wgt = [10, 20, 30, 40, 50];
|
||||
const val = [50, 120, 150, 210, 240];
|
||||
const cap = 50;
|
||||
@@ -95,19 +95,19 @@ const n = wgt.length;
|
||||
|
||||
// Brute-force search
|
||||
let res = knapsackDFS(wgt, val, n, cap);
|
||||
console.log(`Maximum item value not exceeding knapsack capacity is ${res}`);
|
||||
console.log(`Maximum item value within the knapsack capacity: ${res}`);
|
||||
|
||||
// Memoization search
|
||||
// Memoized search
|
||||
const mem = Array.from({ length: n + 1 }, () =>
|
||||
Array.from({ length: cap + 1 }, () => -1)
|
||||
);
|
||||
res = knapsackDFSMem(wgt, val, mem, n, cap);
|
||||
console.log(`Maximum item value not exceeding knapsack capacity is ${res}`);
|
||||
console.log(`Maximum item value within the knapsack capacity: ${res}`);
|
||||
|
||||
// Dynamic programming
|
||||
res = knapsackDP(wgt, val, cap);
|
||||
console.log(`Maximum item value not exceeding knapsack capacity is ${res}`);
|
||||
console.log(`Maximum item value within the knapsack capacity: ${res}`);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = knapsackDPComp(wgt, val, cap);
|
||||
console.log(`Maximum item value not exceeding knapsack capacity is ${res}`);
|
||||
console.log(`Maximum item value within the knapsack capacity: ${res}`);
|
||||
|
||||
@@ -4,25 +4,25 @@
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Minimum cost climbing stairs: Dynamic programming */
|
||||
/* Minimum cost to climb stairs: dynamic programming */
|
||||
function minCostClimbingStairsDP(cost) {
|
||||
const n = cost.length - 1;
|
||||
if (n === 1 || n === 2) {
|
||||
return cost[n];
|
||||
}
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
// Initialize the dp table to store subproblem solutions
|
||||
const dp = new Array(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 (let i = 3; i <= n; i++) {
|
||||
dp[i] = Math.min(dp[i - 1], dp[i - 2]) + cost[i];
|
||||
}
|
||||
return dp[n];
|
||||
}
|
||||
|
||||
/* Minimum cost climbing stairs: Space-optimized dynamic programming */
|
||||
/* Minimum cost to climb stairs: space-optimized dynamic programming */
|
||||
function minCostClimbingStairsDPComp(cost) {
|
||||
const n = cost.length - 1;
|
||||
if (n === 1 || n === 2) {
|
||||
@@ -38,12 +38,12 @@ function minCostClimbingStairsDPComp(cost) {
|
||||
return b;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const cost = [0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1];
|
||||
console.log('Input stair cost list is:', cost);
|
||||
console.log('Input list of stair costs:', cost);
|
||||
|
||||
let res = minCostClimbingStairsDP(cost);
|
||||
console.log(`Minimum cost to climb stairs is: ${res}`);
|
||||
console.log(`Minimum cost to climb the stairs: ${res}`);
|
||||
|
||||
res = minCostClimbingStairsDPComp(cost);
|
||||
console.log(`Minimum cost to climb stairs is: ${res}`);
|
||||
console.log(`Minimum cost to climb the stairs: ${res}`);
|
||||
|
||||
@@ -4,63 +4,63 @@
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Minimum path sum: Brute-force search */
|
||||
/* Minimum path sum: brute-force search */
|
||||
function minPathSumDFS(grid, i, 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 Infinity;
|
||||
}
|
||||
// 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)
|
||||
const up = minPathSumDFS(grid, i - 1, j);
|
||||
const left = minPathSumDFS(grid, i, j - 1);
|
||||
// Return the minimum path cost from top-left to (i, j)
|
||||
// Return the minimum path cost from the top-left corner to (i, j)
|
||||
return Math.min(left, up) + grid[i][j];
|
||||
}
|
||||
|
||||
/* Minimum path sum: Memoization search */
|
||||
/* Minimum path sum: memoized search */
|
||||
function minPathSumDFSMem(grid, mem, i, 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 Infinity;
|
||||
}
|
||||
// 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
|
||||
const up = minPathSumDFSMem(grid, mem, i - 1, j);
|
||||
const left = minPathSumDFSMem(grid, mem, i, j - 1);
|
||||
// Record and return the minimum path cost from top-left to (i, j)
|
||||
// Record and return the minimum path cost from the top-left corner to (i, j)
|
||||
mem[i][j] = Math.min(left, up) + grid[i][j];
|
||||
return mem[i][j];
|
||||
}
|
||||
|
||||
/* Minimum path sum: Dynamic programming */
|
||||
/* Minimum path sum: dynamic programming */
|
||||
function minPathSumDP(grid) {
|
||||
const n = grid.length,
|
||||
m = grid[0].length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
const dp = Array.from({ length: n }, () =>
|
||||
Array.from({ length: m }, () => 0)
|
||||
);
|
||||
dp[0][0] = grid[0][0];
|
||||
// State transition: first row
|
||||
// State transitions: first row
|
||||
for (let j = 1; j < m; j++) {
|
||||
dp[0][j] = dp[0][j - 1] + grid[0][j];
|
||||
}
|
||||
// State transition: first column
|
||||
// State transitions: first column
|
||||
for (let 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 (let i = 1; i < n; i++) {
|
||||
for (let j = 1; j < m; j++) {
|
||||
dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
|
||||
@@ -69,22 +69,22 @@ function minPathSumDP(grid) {
|
||||
return dp[n - 1][m - 1];
|
||||
}
|
||||
|
||||
/* Minimum path sum: Space-optimized dynamic programming */
|
||||
/* Minimum path sum: space-optimized dynamic programming */
|
||||
function minPathSumDPComp(grid) {
|
||||
const n = grid.length,
|
||||
m = grid[0].length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
const dp = new Array(m);
|
||||
// State transition: first row
|
||||
// State transitions: first row
|
||||
dp[0] = grid[0][0];
|
||||
for (let j = 1; j < m; j++) {
|
||||
dp[j] = dp[j - 1] + grid[0][j];
|
||||
}
|
||||
// State transition: rest of the rows
|
||||
// State transitions: remaining rows
|
||||
for (let 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 (let j = 1; j < m; j++) {
|
||||
dp[j] = Math.min(dp[j - 1], dp[j]) + grid[i][j];
|
||||
}
|
||||
@@ -92,7 +92,7 @@ function minPathSumDPComp(grid) {
|
||||
return dp[m - 1];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const grid = [
|
||||
[1, 3, 1, 5],
|
||||
[2, 2, 4, 2],
|
||||
@@ -103,19 +103,19 @@ const n = grid.length,
|
||||
m = grid[0].length;
|
||||
// Brute-force search
|
||||
let res = minPathSumDFS(grid, n - 1, m - 1);
|
||||
console.log(`Minimum path sum from top-left to bottom-right is ${res}`);
|
||||
console.log(`Minimum path sum from the top-left to the bottom-right: ${res}`);
|
||||
|
||||
// Memoization search
|
||||
// Memoized search
|
||||
const mem = Array.from({ length: n }, () =>
|
||||
Array.from({ length: m }, () => -1)
|
||||
);
|
||||
res = minPathSumDFSMem(grid, mem, n - 1, m - 1);
|
||||
console.log(`Minimum path sum from top-left to bottom-right is ${res}`);
|
||||
console.log(`Minimum path sum from the top-left to the bottom-right: ${res}`);
|
||||
|
||||
// Dynamic programming
|
||||
res = minPathSumDP(grid);
|
||||
console.log(`Minimum path sum from top-left to bottom-right is ${res}`);
|
||||
console.log(`Minimum path sum from the top-left to the bottom-right: ${res}`);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = minPathSumDPComp(grid);
|
||||
console.log(`Minimum path sum from top-left to bottom-right is ${res}`);
|
||||
console.log(`Minimum path sum from the top-left to the bottom-right: ${res}`);
|
||||
|
||||
@@ -4,21 +4,21 @@
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Unbounded knapsack: Dynamic programming */
|
||||
/* Unbounded knapsack: dynamic programming */
|
||||
function unboundedKnapsackDP(wgt, val, cap) {
|
||||
const n = wgt.length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
const dp = Array.from({ length: n + 1 }, () =>
|
||||
Array.from({ length: cap + 1 }, () => 0)
|
||||
);
|
||||
// State transition
|
||||
// State transitions
|
||||
for (let i = 1; i <= n; i++) {
|
||||
for (let c = 1; c <= cap; c++) {
|
||||
if (wgt[i - 1] > c) {
|
||||
// If exceeds knapsack capacity, don't select item i
|
||||
// If item i exceeds the remaining capacity, do not choose it
|
||||
dp[i][c] = dp[i - 1][c];
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
dp[i][c] = Math.max(
|
||||
dp[i - 1][c],
|
||||
dp[i][c - wgt[i - 1]] + val[i - 1]
|
||||
@@ -29,19 +29,19 @@ function unboundedKnapsackDP(wgt, val, cap) {
|
||||
return dp[n][cap];
|
||||
}
|
||||
|
||||
/* Unbounded knapsack: Space-optimized dynamic programming */
|
||||
/* Unbounded knapsack: space-optimized dynamic programming */
|
||||
function unboundedKnapsackDPComp(wgt, val, cap) {
|
||||
const n = wgt.length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
const dp = Array.from({ length: cap + 1 }, () => 0);
|
||||
// State transition
|
||||
// State transitions
|
||||
for (let i = 1; i <= n; i++) {
|
||||
for (let c = 1; c <= cap; c++) {
|
||||
if (wgt[i - 1] > c) {
|
||||
// If exceeds knapsack capacity, don't select item i
|
||||
// If item i exceeds the remaining capacity, do not choose it
|
||||
dp[c] = dp[c];
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
dp[c] = Math.max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
@@ -49,15 +49,15 @@ function unboundedKnapsackDPComp(wgt, val, cap) {
|
||||
return dp[cap];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const wgt = [1, 2, 3];
|
||||
const val = [5, 11, 15];
|
||||
const cap = 4;
|
||||
|
||||
// Dynamic programming
|
||||
let res = unboundedKnapsackDP(wgt, val, cap);
|
||||
console.log(`Maximum item value not exceeding knapsack capacity is ${res}`);
|
||||
console.log(`Maximum item value within the knapsack capacity: ${res}`);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = unboundedKnapsackDPComp(wgt, val, cap);
|
||||
console.log(`Maximum item value not exceeding knapsack capacity is ${res}`);
|
||||
console.log(`Maximum item value within the knapsack capacity: ${res}`);
|
||||
|
||||
Reference in New Issue
Block a user