mirror of
https://github.com/krahets/hello-algo.git
synced 2026-04-07 20:50:58 +08:00
Translate all code to English (#1836)
* Review the EN heading format. * Fix pythontutor headings. * Fix pythontutor headings. * bug fixes * Fix headings in **/summary.md * Revisit the CN-to-EN translation for Python code using Claude-4.5 * Revisit the CN-to-EN translation for Java code using Claude-4.5 * Revisit the CN-to-EN translation for Cpp code using Claude-4.5. * Fix the dictionary. * Fix cpp code translation for the multipart strings. * Translate Go code to English. * Update workflows to test EN code. * Add EN translation for C. * Add EN translation for CSharp. * Add EN translation for Swift. * Trigger the CI check. * Revert. * Update en/hash_map.md * Add the EN version of Dart code. * Add the EN version of Kotlin code. * Add missing code files. * Add the EN version of JavaScript code. * Add the EN version of TypeScript code. * Fix the workflows. * Add the EN version of Ruby code. * Add the EN version of Rust code. * Update the CI check for the English version code. * Update Python CI check. * Fix cmakelists for en/C code. * Fix Ruby comments
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* File: climbing_stairs_backtrack.js
|
||||
* Created Time: 2023-07-26
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking */
|
||||
function backtrack(choices, state, n, res) {
|
||||
// When climbing to the n-th stair, add 1 to the solution count
|
||||
if (state === n) res.set(0, res.get(0) + 1);
|
||||
// Traverse all choices
|
||||
for (const choice of choices) {
|
||||
// Pruning: not allowed to go beyond the n-th stair
|
||||
if (state + choice > n) continue;
|
||||
// Attempt: make choice, update state
|
||||
backtrack(choices, state + choice, n, res);
|
||||
// Backtrack
|
||||
}
|
||||
}
|
||||
|
||||
/* 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 res = new Map();
|
||||
res.set(0, 0); // Use res[0] to record the solution count
|
||||
backtrack(choices, state, n, res);
|
||||
return res.get(0);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const n = 9;
|
||||
const res = climbingStairsBacktrack(n);
|
||||
console.log(`Climbing ${n} stairs has ${res} solutions`);
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* File: climbing_stairs_constraint_dp.js
|
||||
* Created Time: 2023-08-23
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Climbing stairs with constraint: Dynamic programming */
|
||||
function climbingStairsConstraintDP(n) {
|
||||
if (n === 1 || n === 2) {
|
||||
return 1;
|
||||
}
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
const dp = Array.from(new Array(n + 1), () => new Array(3));
|
||||
// Initial state: preset the solution to the smallest subproblem
|
||||
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
|
||||
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];
|
||||
}
|
||||
return dp[n][1] + dp[n][2];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const n = 9;
|
||||
const res = climbingStairsConstraintDP(n);
|
||||
console.log(`Climbing ${n} stairs has ${res} solutions`);
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* File: climbing_stairs_dfs.js
|
||||
* Created Time: 2023-07-26
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Search */
|
||||
function dfs(i) {
|
||||
// Known dp[1] and dp[2], 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 */
|
||||
function climbingStairsDFS(n) {
|
||||
return dfs(n);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const n = 9;
|
||||
const res = climbingStairsDFS(n);
|
||||
console.log(`Climbing ${n} stairs has ${res} solutions`);
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* File: climbing_stairs_dfs_mem.js
|
||||
* Created Time: 2023-07-26
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Memoization search */
|
||||
function dfs(i, mem) {
|
||||
// Known dp[1] and dp[2], return them
|
||||
if (i === 1 || i === 2) return i;
|
||||
// If record dp[i] exists, 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);
|
||||
// Record dp[i]
|
||||
mem[i] = count;
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Climbing stairs: Memoization search */
|
||||
function climbingStairsDFSMem(n) {
|
||||
// mem[i] records the total number of solutions to climb to the i-th stair, -1 means no record
|
||||
const mem = new Array(n + 1).fill(-1);
|
||||
return dfs(n, mem);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const n = 9;
|
||||
const res = climbingStairsDFSMem(n);
|
||||
console.log(`Climbing ${n} stairs has ${res} solutions`);
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* File: climbing_stairs_dp.js
|
||||
* Created Time: 2023-07-26
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Climbing stairs: Dynamic programming */
|
||||
function climbingStairsDP(n) {
|
||||
if (n === 1 || n === 2) return n;
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
const dp = new Array(n + 1).fill(-1);
|
||||
// Initial state: preset the solution to the smallest subproblem
|
||||
dp[1] = 1;
|
||||
dp[2] = 2;
|
||||
// State transition: gradually solve larger subproblems from 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 */
|
||||
function climbingStairsDPComp(n) {
|
||||
if (n === 1 || n === 2) return n;
|
||||
let a = 1,
|
||||
b = 2;
|
||||
for (let i = 3; i <= n; i++) {
|
||||
const tmp = b;
|
||||
b = a + b;
|
||||
a = tmp;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const n = 9;
|
||||
let res = climbingStairsDP(n);
|
||||
console.log(`Climbing ${n} stairs has ${res} solutions`);
|
||||
res = climbingStairsDPComp(n);
|
||||
console.log(`Climbing ${n} stairs has ${res} solutions`);
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* File: coin_change.js
|
||||
* Created Time: 2023-08-23
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Coin change: Dynamic programming */
|
||||
function coinChangeDP(coins, amt) {
|
||||
const n = coins.length;
|
||||
const MAX = amt + 1;
|
||||
// Initialize dp table
|
||||
const dp = Array.from({ length: n + 1 }, () =>
|
||||
Array.from({ length: amt + 1 }, () => 0)
|
||||
);
|
||||
// State transition: first row and first column
|
||||
for (let a = 1; a <= amt; a++) {
|
||||
dp[0][a] = MAX;
|
||||
}
|
||||
// State transition: rest of the 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
|
||||
dp[i][a] = dp[i - 1][a];
|
||||
} else {
|
||||
// The smaller value between not selecting and selecting coin i
|
||||
dp[i][a] = Math.min(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][amt] !== MAX ? dp[n][amt] : -1;
|
||||
}
|
||||
|
||||
/* Coin change: Space-optimized dynamic programming */
|
||||
function coinChangeDPComp(coins, amt) {
|
||||
const n = coins.length;
|
||||
const MAX = amt + 1;
|
||||
// Initialize dp table
|
||||
const dp = Array.from({ length: amt + 1 }, () => MAX);
|
||||
dp[0] = 0;
|
||||
// State transition
|
||||
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
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// The smaller value between not selecting and selecting coin i
|
||||
dp[a] = Math.min(dp[a], dp[a - coins[i - 1]] + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[amt] !== MAX ? dp[amt] : -1;
|
||||
}
|
||||
|
||||
/* 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}`);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = coinChangeDPComp(coins, amt);
|
||||
console.log(`Minimum coins needed to make target amount is ${res}`);
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* File: coin_change_ii.js
|
||||
* Created Time: 2023-08-23
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Coin change II: Dynamic programming */
|
||||
function coinChangeIIDP(coins, amt) {
|
||||
const n = coins.length;
|
||||
// Initialize dp table
|
||||
const dp = Array.from({ length: n + 1 }, () =>
|
||||
Array.from({ length: amt + 1 }, () => 0)
|
||||
);
|
||||
// Initialize first column
|
||||
for (let i = 0; i <= n; i++) {
|
||||
dp[i][0] = 1;
|
||||
}
|
||||
// State transition
|
||||
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
|
||||
dp[i][a] = dp[i - 1][a];
|
||||
} else {
|
||||
// Sum of the two options: not selecting and selecting coin i
|
||||
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]];
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][amt];
|
||||
}
|
||||
|
||||
/* Coin change II: Space-optimized dynamic programming */
|
||||
function coinChangeIIDPComp(coins, amt) {
|
||||
const n = coins.length;
|
||||
// Initialize dp table
|
||||
const dp = Array.from({ length: amt + 1 }, () => 0);
|
||||
dp[0] = 1;
|
||||
// State transition
|
||||
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
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// Sum of the two options: not selecting and selecting coin i
|
||||
dp[a] = dp[a] + dp[a - coins[i - 1]];
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[amt];
|
||||
}
|
||||
|
||||
/* 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}`);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = coinChangeIIDPComp(coins, amt);
|
||||
console.log(`Number of coin combinations to make target amount is ${res}`);
|
||||
135
en/codes/javascript/chapter_dynamic_programming/edit_distance.js
Normal file
135
en/codes/javascript/chapter_dynamic_programming/edit_distance.js
Normal file
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* File: edit_distance.js
|
||||
* Created Time: 2023-08-23
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Edit distance: Brute-force search */
|
||||
function editDistanceDFS(s, t, i, j) {
|
||||
// If both s and t are empty, return 0
|
||||
if (i === 0 && j === 0) return 0;
|
||||
|
||||
// If s is empty, return length of t
|
||||
if (i === 0) return j;
|
||||
|
||||
// If t is empty, return length of s
|
||||
if (j === 0) return i;
|
||||
|
||||
// If two characters are equal, skip both characters
|
||||
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
|
||||
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 Math.min(insert, del, replace) + 1;
|
||||
}
|
||||
|
||||
/* Edit distance: Memoization search */
|
||||
function editDistanceDFSMem(s, t, mem, i, j) {
|
||||
// If both s and t are empty, return 0
|
||||
if (i === 0 && j === 0) return 0;
|
||||
|
||||
// If s is empty, return length of t
|
||||
if (i === 0) return j;
|
||||
|
||||
// If t is empty, return length of s
|
||||
if (j === 0) return i;
|
||||
|
||||
// If there's a record, return it directly
|
||||
if (mem[i][j] !== -1) return mem[i][j];
|
||||
|
||||
// If two characters are equal, skip both characters
|
||||
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
|
||||
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
|
||||
mem[i][j] = Math.min(insert, del, replace) + 1;
|
||||
return mem[i][j];
|
||||
}
|
||||
|
||||
/* 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
|
||||
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
|
||||
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
|
||||
dp[i][j] = dp[i - 1][j - 1];
|
||||
} else {
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
dp[i][j] =
|
||||
Math.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 */
|
||||
function editDistanceDPComp(s, t) {
|
||||
const n = s.length,
|
||||
m = t.length;
|
||||
const dp = new Array(m + 1).fill(0);
|
||||
// State transition: first row
|
||||
for (let j = 1; j <= m; j++) {
|
||||
dp[j] = j;
|
||||
}
|
||||
// State transition: rest of the rows
|
||||
for (let i = 1; i <= n; i++) {
|
||||
// State transition: first column
|
||||
let leftup = dp[0]; // Temporarily store dp[i-1, j-1]
|
||||
dp[0] = i;
|
||||
// State transition: rest of the 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
|
||||
dp[j] = leftup;
|
||||
} else {
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
dp[j] = Math.min(dp[j - 1], dp[j], leftup) + 1;
|
||||
}
|
||||
leftup = temp; // Update for next round's dp[i-1, j-1]
|
||||
}
|
||||
}
|
||||
return dp[m];
|
||||
}
|
||||
|
||||
const s = 'bag';
|
||||
const t = 'pack';
|
||||
const n = s.length,
|
||||
m = t.length;
|
||||
|
||||
// Brute-force search
|
||||
let res = editDistanceDFS(s, t, n, m);
|
||||
console.log(`Changing ${s} to ${t} requires minimum ${res} edits`);
|
||||
|
||||
// Memoization 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`);
|
||||
|
||||
// Dynamic programming
|
||||
res = editDistanceDP(s, t);
|
||||
console.log(`Changing ${s} to ${t} requires minimum ${res} edits`);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = editDistanceDPComp(s, t);
|
||||
console.log(`Changing ${s} to ${t} requires minimum ${res} edits`);
|
||||
113
en/codes/javascript/chapter_dynamic_programming/knapsack.js
Normal file
113
en/codes/javascript/chapter_dynamic_programming/knapsack.js
Normal file
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* File: knapsack.js
|
||||
* Created Time: 2023-08-23
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* 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 (i === 0 || c === 0) {
|
||||
return 0;
|
||||
}
|
||||
// If exceeds knapsack capacity, can only choose not to put it in
|
||||
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
|
||||
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 Math.max(no, yes);
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Memoization search */
|
||||
function knapsackDFSMem(wgt, val, mem, i, c) {
|
||||
// If all items have been selected or knapsack has no remaining capacity, return value 0
|
||||
if (i === 0 || c === 0) {
|
||||
return 0;
|
||||
}
|
||||
// If there's a record, 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 (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
|
||||
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
|
||||
mem[i][c] = Math.max(no, yes);
|
||||
return mem[i][c];
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Dynamic programming */
|
||||
function knapsackDP(wgt, val, cap) {
|
||||
const n = wgt.length;
|
||||
// Initialize dp table
|
||||
const dp = Array(n + 1)
|
||||
.fill(0)
|
||||
.map(() => Array(cap + 1).fill(0));
|
||||
// State transition
|
||||
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
|
||||
dp[i][c] = dp[i - 1][c];
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
dp[i][c] = Math.max(
|
||||
dp[i - 1][c],
|
||||
dp[i - 1][c - wgt[i - 1]] + val[i - 1]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][cap];
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Space-optimized dynamic programming */
|
||||
function knapsackDPComp(wgt, val, cap) {
|
||||
const n = wgt.length;
|
||||
// Initialize dp table
|
||||
const dp = Array(cap + 1).fill(0);
|
||||
// State transition
|
||||
for (let i = 1; i <= n; i++) {
|
||||
// Traverse in reverse order
|
||||
for (let c = cap; c >= 1; c--) {
|
||||
if (wgt[i - 1] <= c) {
|
||||
// The larger value between not selecting and selecting item i
|
||||
dp[c] = Math.max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const wgt = [10, 20, 30, 40, 50];
|
||||
const val = [50, 120, 150, 210, 240];
|
||||
const cap = 50;
|
||||
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}`);
|
||||
|
||||
// Memoization 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}`);
|
||||
|
||||
// Dynamic programming
|
||||
res = knapsackDP(wgt, val, cap);
|
||||
console.log(`Maximum item value not exceeding knapsack capacity is ${res}`);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = knapsackDPComp(wgt, val, cap);
|
||||
console.log(`Maximum item value not exceeding knapsack capacity is ${res}`);
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* File: min_cost_climbing_stairs_dp.js
|
||||
* Created Time: 2023-08-23
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Minimum cost climbing 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
|
||||
const dp = new Array(n + 1);
|
||||
// Initial state: preset the solution to the smallest subproblem
|
||||
dp[1] = cost[1];
|
||||
dp[2] = cost[2];
|
||||
// State transition: gradually solve larger subproblems from 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 */
|
||||
function minCostClimbingStairsDPComp(cost) {
|
||||
const n = cost.length - 1;
|
||||
if (n === 1 || n === 2) {
|
||||
return cost[n];
|
||||
}
|
||||
let a = cost[1],
|
||||
b = cost[2];
|
||||
for (let i = 3; i <= n; i++) {
|
||||
const tmp = b;
|
||||
b = Math.min(a, tmp) + cost[i];
|
||||
a = tmp;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const cost = [0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1];
|
||||
console.log('Input stair cost list is:', cost);
|
||||
|
||||
let res = minCostClimbingStairsDP(cost);
|
||||
console.log(`Minimum cost to climb stairs is: ${res}`);
|
||||
|
||||
res = minCostClimbingStairsDPComp(cost);
|
||||
console.log(`Minimum cost to climb stairs is: ${res}`);
|
||||
121
en/codes/javascript/chapter_dynamic_programming/min_path_sum.js
Normal file
121
en/codes/javascript/chapter_dynamic_programming/min_path_sum.js
Normal file
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* File: min_path_sum.js
|
||||
* Created Time: 2023-08-23
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Minimum path sum: Brute-force search */
|
||||
function minPathSumDFS(grid, i, j) {
|
||||
// If it's the top-left cell, terminate the search
|
||||
if (i === 0 && j === 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// If row or column index is out of bounds, return +∞ cost
|
||||
if (i < 0 || j < 0) {
|
||||
return Infinity;
|
||||
}
|
||||
// Calculate the minimum path cost from top-left 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 Math.min(left, up) + grid[i][j];
|
||||
}
|
||||
|
||||
/* Minimum path sum: Memoization search */
|
||||
function minPathSumDFSMem(grid, mem, i, j) {
|
||||
// If it's the top-left cell, terminate the search
|
||||
if (i === 0 && j === 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// If row or column index is out of bounds, return +∞ cost
|
||||
if (i < 0 || j < 0) {
|
||||
return Infinity;
|
||||
}
|
||||
// If there's a record, return it directly
|
||||
if (mem[i][j] !== -1) {
|
||||
return mem[i][j];
|
||||
}
|
||||
// Minimum path cost for left and upper cells
|
||||
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)
|
||||
mem[i][j] = Math.min(left, up) + grid[i][j];
|
||||
return mem[i][j];
|
||||
}
|
||||
|
||||
/* Minimum path sum: Dynamic programming */
|
||||
function minPathSumDP(grid) {
|
||||
const n = grid.length,
|
||||
m = grid[0].length;
|
||||
// Initialize dp table
|
||||
const dp = Array.from({ length: n }, () =>
|
||||
Array.from({ length: m }, () => 0)
|
||||
);
|
||||
dp[0][0] = grid[0][0];
|
||||
// State transition: first row
|
||||
for (let j = 1; j < m; j++) {
|
||||
dp[0][j] = dp[0][j - 1] + grid[0][j];
|
||||
}
|
||||
// State transition: 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
|
||||
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];
|
||||
}
|
||||
}
|
||||
return dp[n - 1][m - 1];
|
||||
}
|
||||
|
||||
/* Minimum path sum: Space-optimized dynamic programming */
|
||||
function minPathSumDPComp(grid) {
|
||||
const n = grid.length,
|
||||
m = grid[0].length;
|
||||
// Initialize dp table
|
||||
const dp = new Array(m);
|
||||
// State transition: 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
|
||||
for (let i = 1; i < n; i++) {
|
||||
// State transition: first column
|
||||
dp[0] = dp[0] + grid[i][0];
|
||||
// State transition: rest of the columns
|
||||
for (let j = 1; j < m; j++) {
|
||||
dp[j] = Math.min(dp[j - 1], dp[j]) + grid[i][j];
|
||||
}
|
||||
}
|
||||
return dp[m - 1];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const grid = [
|
||||
[1, 3, 1, 5],
|
||||
[2, 2, 4, 2],
|
||||
[5, 3, 2, 1],
|
||||
[4, 3, 5, 2],
|
||||
];
|
||||
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}`);
|
||||
|
||||
// Memoization 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}`);
|
||||
|
||||
// Dynamic programming
|
||||
res = minPathSumDP(grid);
|
||||
console.log(`Minimum path sum from top-left to bottom-right is ${res}`);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = minPathSumDPComp(grid);
|
||||
console.log(`Minimum path sum from top-left to bottom-right is ${res}`);
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* File: unbounded_knapsack.js
|
||||
* Created Time: 2023-08-23
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Unbounded knapsack: Dynamic programming */
|
||||
function unboundedKnapsackDP(wgt, val, cap) {
|
||||
const n = wgt.length;
|
||||
// Initialize dp table
|
||||
const dp = Array.from({ length: n + 1 }, () =>
|
||||
Array.from({ length: cap + 1 }, () => 0)
|
||||
);
|
||||
// State transition
|
||||
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
|
||||
dp[i][c] = dp[i - 1][c];
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
dp[i][c] = Math.max(
|
||||
dp[i - 1][c],
|
||||
dp[i][c - wgt[i - 1]] + val[i - 1]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][cap];
|
||||
}
|
||||
|
||||
/* Unbounded knapsack: Space-optimized dynamic programming */
|
||||
function unboundedKnapsackDPComp(wgt, val, cap) {
|
||||
const n = wgt.length;
|
||||
// Initialize dp table
|
||||
const dp = Array.from({ length: cap + 1 }, () => 0);
|
||||
// State transition
|
||||
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
|
||||
dp[c] = dp[c];
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
dp[c] = Math.max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap];
|
||||
}
|
||||
|
||||
/* 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}`);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = unboundedKnapsackDPComp(wgt, val, cap);
|
||||
console.log(`Maximum item value not exceeding knapsack capacity is ${res}`);
|
||||
Reference in New Issue
Block a user