mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-14 01:38:18 +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:
@@ -4,51 +4,51 @@
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: N queens */
|
||||
/* Backtracking: n-queens */
|
||||
function backtrack(row, n, state, res, cols, diags1, diags2) {
|
||||
// When all rows are placed, record the solution
|
||||
// Record a solution when a queen has been placed in every row
|
||||
if (row === n) {
|
||||
res.push(state.map((row) => row.slice()));
|
||||
return;
|
||||
}
|
||||
// Traverse all columns
|
||||
// Iterate over all columns
|
||||
for (let col = 0; col < n; col++) {
|
||||
// Calculate the main diagonal and anti-diagonal corresponding to this cell
|
||||
// Calculate the main-diagonal and anti-diagonal indices for this square
|
||||
const diag1 = row - col + n - 1;
|
||||
const diag2 = row + col;
|
||||
// Pruning: do not allow queens to exist in the column, main diagonal, and anti-diagonal of this cell
|
||||
// Prune: the square must have no queen in its column, main diagonal, or anti-diagonal
|
||||
if (!cols[col] && !diags1[diag1] && !diags2[diag2]) {
|
||||
// Attempt: place the queen in this cell
|
||||
// Try: place a queen on this square
|
||||
state[row][col] = 'Q';
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = true;
|
||||
// Place the next row
|
||||
// Place a queen in the next row
|
||||
backtrack(row + 1, n, state, res, cols, diags1, diags2);
|
||||
// Backtrack: restore this cell to an empty cell
|
||||
// Backtrack: restore this square to empty
|
||||
state[row][col] = '#';
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Solve N queens */
|
||||
/* Solve the n-queens problem */
|
||||
function nQueens(n) {
|
||||
// Initialize an n*n chessboard, where 'Q' represents a queen and '#' represents an empty cell
|
||||
// Initialize an n*n board, where 'Q' represents a queen and '#' represents an empty square
|
||||
const state = Array.from({ length: n }, () => Array(n).fill('#'));
|
||||
const cols = Array(n).fill(false); // Record whether there is a queen in the column
|
||||
const diags1 = Array(2 * n - 1).fill(false); // Record whether there is a queen on the main diagonal
|
||||
const diags2 = Array(2 * n - 1).fill(false); // Record whether there is a queen on the anti-diagonal
|
||||
const cols = Array(n).fill(false); // Track whether a column contains a queen
|
||||
const diags1 = Array(2 * n - 1).fill(false); // Track whether a main diagonal contains a queen
|
||||
const diags2 = Array(2 * n - 1).fill(false); // Track whether an anti-diagonal contains a queen
|
||||
const res = [];
|
||||
|
||||
backtrack(0, n, state, res, cols, diags1, diags2);
|
||||
return res;
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
// Driver code
|
||||
const n = 4;
|
||||
const res = nQueens(n);
|
||||
|
||||
console.log(`Input board size is ${n}`);
|
||||
console.log(`Total queen placement solutions: ${res.length}`);
|
||||
console.log(`Input board side length: ${n}`);
|
||||
console.log(`Number of queen arrangements: ${res.length}`);
|
||||
res.forEach((state) => {
|
||||
console.log('--------------------');
|
||||
state.forEach((row) => console.log(row));
|
||||
|
||||
@@ -4,23 +4,23 @@
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Permutations I */
|
||||
/* Backtracking: permutations I */
|
||||
function backtrack(state, choices, selected, res) {
|
||||
// When the state length equals the number of elements, record the solution
|
||||
// Record a solution when the state length equals the number of elements
|
||||
if (state.length === choices.length) {
|
||||
res.push([...state]);
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
// Iterate over all choices
|
||||
choices.forEach((choice, i) => {
|
||||
// Pruning: do not allow repeated selection of elements
|
||||
// Prune: do not choose an element more than once
|
||||
if (!selected[i]) {
|
||||
// Attempt: make choice, update state
|
||||
// Try: make a choice and update the state
|
||||
selected[i] = true;
|
||||
state.push(choice);
|
||||
// Proceed to the next round of selection
|
||||
// Proceed to the next choice
|
||||
backtrack(state, choices, selected, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
selected[i] = false;
|
||||
state.pop();
|
||||
}
|
||||
@@ -34,7 +34,7 @@ function permutationsI(nums) {
|
||||
return res;
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
// Driver code
|
||||
const nums = [1, 2, 3];
|
||||
const res = permutationsI(nums);
|
||||
|
||||
|
||||
@@ -4,25 +4,25 @@
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Permutations II */
|
||||
/* Backtracking: permutations II */
|
||||
function backtrack(state, choices, selected, res) {
|
||||
// When the state length equals the number of elements, record the solution
|
||||
// Record a solution when the state length equals the number of elements
|
||||
if (state.length === choices.length) {
|
||||
res.push([...state]);
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
// Iterate over all choices
|
||||
const duplicated = new Set();
|
||||
choices.forEach((choice, i) => {
|
||||
// Pruning: do not allow repeated selection of elements and do not allow repeated selection of equal elements
|
||||
// Prune: do not reuse an element or choose the same value again at this depth
|
||||
if (!selected[i] && !duplicated.has(choice)) {
|
||||
// Attempt: make choice, update state
|
||||
duplicated.add(choice); // Record the selected element value
|
||||
// Try: make a choice and update the state
|
||||
duplicated.add(choice); // Record the chosen value
|
||||
selected[i] = true;
|
||||
state.push(choice);
|
||||
// Proceed to the next round of selection
|
||||
// Proceed to the next choice
|
||||
backtrack(state, choices, selected, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
selected[i] = false;
|
||||
state.pop();
|
||||
}
|
||||
@@ -36,7 +36,7 @@ function permutationsII(nums) {
|
||||
return res;
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
// Driver code
|
||||
const nums = [1, 2, 2];
|
||||
const res = permutationsII(nums);
|
||||
|
||||
|
||||
@@ -7,22 +7,22 @@
|
||||
const { arrToTree } = require('../modules/TreeNode');
|
||||
const { printTree } = require('../modules/PrintUtil');
|
||||
|
||||
/* Preorder traversal: Example 1 */
|
||||
/* Preorder traversal: example 1 */
|
||||
function preOrder(root, res) {
|
||||
if (root === null) {
|
||||
return;
|
||||
}
|
||||
if (root.val === 7) {
|
||||
// Record solution
|
||||
// Record the solution
|
||||
res.push(root);
|
||||
}
|
||||
preOrder(root.left, res);
|
||||
preOrder(root.right, res);
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
// Driver code
|
||||
const root = arrToTree([1, 7, 3, 4, 5, 6, 7]);
|
||||
console.log('\nInitialize binary tree');
|
||||
console.log('\nInitialize the binary tree');
|
||||
printTree(root);
|
||||
|
||||
// Preorder traversal
|
||||
|
||||
@@ -7,15 +7,15 @@
|
||||
const { arrToTree } = require('../modules/TreeNode');
|
||||
const { printTree } = require('../modules/PrintUtil');
|
||||
|
||||
/* Preorder traversal: Example 2 */
|
||||
/* Preorder traversal: example 2 */
|
||||
function preOrder(root, path, res) {
|
||||
if (root === null) {
|
||||
return;
|
||||
}
|
||||
// Attempt
|
||||
// Try
|
||||
path.push(root);
|
||||
if (root.val === 7) {
|
||||
// Record solution
|
||||
// Record the solution
|
||||
res.push([...path]);
|
||||
}
|
||||
preOrder(root.left, path, res);
|
||||
@@ -24,9 +24,9 @@ function preOrder(root, path, res) {
|
||||
path.pop();
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
// Driver code
|
||||
const root = arrToTree([1, 7, 3, 4, 5, 6, 7]);
|
||||
console.log('\nInitialize binary tree');
|
||||
console.log('\nInitialize the binary tree');
|
||||
printTree(root);
|
||||
|
||||
// Preorder traversal
|
||||
@@ -34,7 +34,7 @@ const path = [];
|
||||
const res = [];
|
||||
preOrder(root, path, res);
|
||||
|
||||
console.log('\nOutput all paths from root node to node 7');
|
||||
console.log('\nOutput all paths from the root to nodes with value 7');
|
||||
res.forEach((path) => {
|
||||
console.log(path.map((node) => node.val));
|
||||
});
|
||||
|
||||
@@ -7,16 +7,16 @@
|
||||
const { arrToTree } = require('../modules/TreeNode');
|
||||
const { printTree } = require('../modules/PrintUtil');
|
||||
|
||||
/* Preorder traversal: Example 3 */
|
||||
/* Preorder traversal: example 3 */
|
||||
function preOrder(root, path, res) {
|
||||
// Pruning
|
||||
// Prune
|
||||
if (root === null || root.val === 3) {
|
||||
return;
|
||||
}
|
||||
// Attempt
|
||||
// Try
|
||||
path.push(root);
|
||||
if (root.val === 7) {
|
||||
// Record solution
|
||||
// Record the solution
|
||||
res.push([...path]);
|
||||
}
|
||||
preOrder(root.left, path, res);
|
||||
@@ -25,9 +25,9 @@ function preOrder(root, path, res) {
|
||||
path.pop();
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
// Driver code
|
||||
const root = arrToTree([1, 7, 3, 4, 5, 6, 7]);
|
||||
console.log('\nInitialize binary tree');
|
||||
console.log('\nInitialize the binary tree');
|
||||
printTree(root);
|
||||
|
||||
// Preorder traversal
|
||||
@@ -35,7 +35,7 @@ const path = [];
|
||||
const res = [];
|
||||
preOrder(root, path, res);
|
||||
|
||||
console.log('\nOutput all paths from root node to node 7, paths do not include nodes with value 3');
|
||||
console.log('\nOutput all paths from the root to nodes with value 7 that contain no node with value 3');
|
||||
res.forEach((path) => {
|
||||
console.log(path.map((node) => node.val));
|
||||
});
|
||||
|
||||
@@ -7,62 +7,62 @@
|
||||
const { arrToTree } = require('../modules/TreeNode');
|
||||
const { printTree } = require('../modules/PrintUtil');
|
||||
|
||||
/* Check if the current state is a solution */
|
||||
/* Check whether the current state is a solution */
|
||||
function isSolution(state) {
|
||||
return state && state[state.length - 1]?.val === 7;
|
||||
}
|
||||
|
||||
/* Record solution */
|
||||
/* Record the solution */
|
||||
function recordSolution(state, res) {
|
||||
res.push([...state]);
|
||||
}
|
||||
|
||||
/* Check if the choice is valid under the current state */
|
||||
/* Check whether the choice is valid in the current state */
|
||||
function isValid(state, choice) {
|
||||
return choice !== null && choice.val !== 3;
|
||||
}
|
||||
|
||||
/* Update state */
|
||||
/* Update the state */
|
||||
function makeChoice(state, choice) {
|
||||
state.push(choice);
|
||||
}
|
||||
|
||||
/* Restore state */
|
||||
/* Restore the state */
|
||||
function undoChoice(state) {
|
||||
state.pop();
|
||||
}
|
||||
|
||||
/* Backtracking algorithm: Example 3 */
|
||||
/* Backtracking: example 3 */
|
||||
function backtrack(state, choices, res) {
|
||||
// Check if it is a solution
|
||||
// Check whether this is a solution
|
||||
if (isSolution(state)) {
|
||||
// Record solution
|
||||
// Record the solution
|
||||
recordSolution(state, res);
|
||||
}
|
||||
// Traverse all choices
|
||||
// Iterate over all choices
|
||||
for (const choice of choices) {
|
||||
// Pruning: check if the choice is valid
|
||||
// Prune: check whether the choice is valid
|
||||
if (isValid(state, choice)) {
|
||||
// Attempt: make choice, update state
|
||||
// Try: make a choice and update the state
|
||||
makeChoice(state, choice);
|
||||
// Proceed to the next round of selection
|
||||
// Proceed to the next choice
|
||||
backtrack(state, [choice.left, choice.right], res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
undoChoice(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
// Driver code
|
||||
const root = arrToTree([1, 7, 3, 4, 5, 6, 7]);
|
||||
console.log('\nInitialize binary tree');
|
||||
console.log('\nInitialize the binary tree');
|
||||
printTree(root);
|
||||
|
||||
// Backtracking algorithm
|
||||
const res = [];
|
||||
backtrack([], [root], res);
|
||||
|
||||
console.log('\nOutput all paths from root node to node 7, requiring paths do not include nodes with value 3');
|
||||
console.log('\nOutput all paths from the root to nodes with value 7, requiring that no node on the path has value 3');
|
||||
res.forEach((path) => {
|
||||
console.log(path.map((node) => node.val));
|
||||
});
|
||||
|
||||
@@ -4,26 +4,26 @@
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Subset sum I */
|
||||
/* Backtracking: subset sum I */
|
||||
function backtrack(state, target, choices, start, res) {
|
||||
// When the subset sum equals target, record the solution
|
||||
// Record a solution when the remaining target is zero, so the subset sum equals the original target
|
||||
if (target === 0) {
|
||||
res.push([...state]);
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
// Pruning 2: start traversing from start to avoid generating duplicate subsets
|
||||
// Iterate over all choices
|
||||
// Pruning 2: iterate from start to avoid generating duplicate subsets
|
||||
for (let i = start; i < choices.length; i++) {
|
||||
// Pruning 1: if the subset sum exceeds target, end the loop directly
|
||||
// This is because the array is sorted, and later elements are larger, so the subset sum will definitely exceed target
|
||||
// Pruning 1: exit the loop if the next choice exceeds the remaining target
|
||||
// The array is sorted, so later elements are at least as large and would also exceed the remaining target
|
||||
if (target - choices[i] < 0) {
|
||||
break;
|
||||
}
|
||||
// Attempt: make choice, update target, start
|
||||
// Try: make a choice and update target and start
|
||||
state.push(choices[i]);
|
||||
// Proceed to the next round of selection
|
||||
// Proceed to the next choice
|
||||
backtrack(state, target - choices[i], choices, i, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
state.pop();
|
||||
}
|
||||
}
|
||||
@@ -32,15 +32,15 @@ function backtrack(state, target, choices, start, res) {
|
||||
function subsetSumI(nums, target) {
|
||||
const state = []; // State (subset)
|
||||
nums.sort((a, b) => a - b); // Sort nums
|
||||
const start = 0; // Start point for traversal
|
||||
const res = []; // Result list (subset list)
|
||||
const start = 0; // Starting index for iteration
|
||||
const res = []; // Result list (list of subsets)
|
||||
backtrack(state, target, nums, start, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const nums = [3, 4, 5];
|
||||
const target = 9;
|
||||
const res = subsetSumI(nums, target);
|
||||
console.log(`Input array nums = ${JSON.stringify(nums)}, target = ${target}`);
|
||||
console.log(`All subsets with sum equal to ${target} res = ${JSON.stringify(res)}`);
|
||||
console.log(`All subsets with sum ${target}: res = ${JSON.stringify(res)}`);
|
||||
|
||||
@@ -4,41 +4,41 @@
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Subset sum I */
|
||||
/* Backtracking: subset sum I */
|
||||
function backtrack(state, target, total, choices, res) {
|
||||
// When the subset sum equals target, record the solution
|
||||
// Record a solution when the subset sum equals target
|
||||
if (total === target) {
|
||||
res.push([...state]);
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
// Iterate over all choices
|
||||
for (let i = 0; i < choices.length; i++) {
|
||||
// Pruning: if the subset sum exceeds target, skip this choice
|
||||
// Prune: skip this choice if the subset sum would exceed target
|
||||
if (total + choices[i] > target) {
|
||||
continue;
|
||||
}
|
||||
// Attempt: make choice, update element sum total
|
||||
// Try: make a choice and update the sum total
|
||||
state.push(choices[i]);
|
||||
// Proceed to the next round of selection
|
||||
// Proceed to the next choice
|
||||
backtrack(state, target, total + choices[i], choices, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
state.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/* Solve subset sum I (including duplicate subsets) */
|
||||
/* Solve subset sum I (with duplicate subsets) */
|
||||
function subsetSumINaive(nums, target) {
|
||||
const state = []; // State (subset)
|
||||
const total = 0; // Subset sum
|
||||
const res = []; // Result list (subset list)
|
||||
const res = []; // Result list (list of subsets)
|
||||
backtrack(state, target, total, nums, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const nums = [3, 4, 5];
|
||||
const target = 9;
|
||||
const res = subsetSumINaive(nums, target);
|
||||
console.log(`Input array nums = ${JSON.stringify(nums)}, target = ${target}`);
|
||||
console.log(`All subsets with sum equal to ${target} res = ${JSON.stringify(res)}`);
|
||||
console.log('Please note that this method outputs results containing duplicate sets');
|
||||
console.log(`All subsets with sum ${target}: res = ${JSON.stringify(res)}`);
|
||||
console.log('Note that this method produces duplicate subsets');
|
||||
|
||||
@@ -4,31 +4,31 @@
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Subset sum II */
|
||||
/* Backtracking: subset sum II */
|
||||
function backtrack(state, target, choices, start, res) {
|
||||
// When the subset sum equals target, record the solution
|
||||
// Record a solution when the remaining target is zero, so the subset sum equals the original target
|
||||
if (target === 0) {
|
||||
res.push([...state]);
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
// Pruning 2: start traversing from start to avoid generating duplicate subsets
|
||||
// Pruning 3: start traversing from start to avoid repeatedly selecting the same element
|
||||
// Iterate over all choices
|
||||
// Pruning 2: iterate from start to avoid generating duplicate subsets
|
||||
// Pruning 3: start after the previously chosen index to avoid choosing the same element again
|
||||
for (let i = start; i < choices.length; i++) {
|
||||
// Pruning 1: if the subset sum exceeds target, end the loop directly
|
||||
// This is because the array is sorted, and later elements are larger, so the subset sum will definitely exceed target
|
||||
// Pruning 1: exit the loop if the next choice exceeds the remaining target
|
||||
// The array is sorted, so later elements are at least as large and would also exceed the remaining target
|
||||
if (target - choices[i] < 0) {
|
||||
break;
|
||||
}
|
||||
// Pruning 4: if this element equals the left element, it means this search branch is duplicate, skip it directly
|
||||
// Pruning 4: if this element equals its left neighbor at the same search depth, the branch is a duplicate; skip it
|
||||
if (i > start && choices[i] === choices[i - 1]) {
|
||||
continue;
|
||||
}
|
||||
// Attempt: make choice, update target, start
|
||||
// Try: make a choice and update target and start
|
||||
state.push(choices[i]);
|
||||
// Proceed to the next round of selection
|
||||
// Proceed to the next choice
|
||||
backtrack(state, target - choices[i], choices, i + 1, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
state.pop();
|
||||
}
|
||||
}
|
||||
@@ -37,15 +37,15 @@ function backtrack(state, target, choices, start, res) {
|
||||
function subsetSumII(nums, target) {
|
||||
const state = []; // State (subset)
|
||||
nums.sort((a, b) => a - b); // Sort nums
|
||||
const start = 0; // Start point for traversal
|
||||
const res = []; // Result list (subset list)
|
||||
const start = 0; // Starting index for iteration
|
||||
const res = []; // Result list (list of subsets)
|
||||
backtrack(state, target, nums, start, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const nums = [4, 4, 5];
|
||||
const target = 9;
|
||||
const res = subsetSumII(nums, target);
|
||||
console.log(`Input array nums = ${JSON.stringify(nums)}, target = ${target}`);
|
||||
console.log(`All subsets with sum equal to ${target} res = ${JSON.stringify(res)}`);
|
||||
console.log(`All subsets with sum ${target}: res = ${JSON.stringify(res)}`);
|
||||
|
||||
Reference in New Issue
Block a user