mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-21 11:13:00 +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,40 +6,40 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Backtracking algorithm: N queens */
|
||||
/* Backtracking: n-queens */
|
||||
void backtrack(int row, int n, vector<vector<string>> &state, vector<vector<vector<string>>> &res, vector<bool> &cols,
|
||||
vector<bool> &diags1, vector<bool> &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_back(state);
|
||||
return;
|
||||
}
|
||||
// Traverse all columns
|
||||
// Iterate over all columns
|
||||
for (int 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
|
||||
int diag1 = row - col + n - 1;
|
||||
int 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 */
|
||||
vector<vector<vector<string>>> nQueens(int 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
|
||||
vector<vector<string>> state(n, vector<string>(n, "#"));
|
||||
vector<bool> cols(n, false); // Record whether there is a queen in the column
|
||||
vector<bool> diags1(2 * n - 1, false); // Record whether there is a queen on the main diagonal
|
||||
vector<bool> diags2(2 * n - 1, false); // Record whether there is a queen on the anti-diagonal
|
||||
vector<bool> cols(n, false); // Track whether a column contains a queen
|
||||
vector<bool> diags1(2 * n - 1, false); // Track whether a main diagonal contains a queen
|
||||
vector<bool> diags2(2 * n - 1, false); // Track whether an anti-diagonal contains a queen
|
||||
vector<vector<vector<string>>> res;
|
||||
|
||||
backtrack(0, n, state, res, cols, diags1, diags2);
|
||||
@@ -47,13 +47,13 @@ vector<vector<vector<string>>> nQueens(int n) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int n = 4;
|
||||
vector<vector<vector<string>>> res = nQueens(n);
|
||||
|
||||
cout << "Input board size is " << n << endl;
|
||||
cout << "Total queen placement solutions: " << res.size() << endl;
|
||||
cout << "Board width and height: " << n << endl;
|
||||
cout << "Queen placements: " << res.size() << " solutions" << endl;
|
||||
for (const vector<vector<string>> &state : res) {
|
||||
cout << "--------------------" << endl;
|
||||
for (const vector<string> &row : state) {
|
||||
|
||||
@@ -6,24 +6,24 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Backtracking algorithm: Permutations I */
|
||||
/* Backtracking: permutations I */
|
||||
void backtrack(vector<int> &state, const vector<int> &choices, vector<bool> &selected, vector<vector<int>> &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.size() == choices.size()) {
|
||||
res.push_back(state);
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
// Iterate over all choices
|
||||
for (int i = 0; i < choices.size(); i++) {
|
||||
int choice = choices[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_back(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_back();
|
||||
}
|
||||
@@ -39,7 +39,7 @@ vector<vector<int>> permutationsI(vector<int> nums) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
vector<int> nums = {1, 2, 3};
|
||||
|
||||
|
||||
@@ -6,26 +6,26 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Backtracking algorithm: Permutations II */
|
||||
/* Backtracking: permutations II */
|
||||
void backtrack(vector<int> &state, const vector<int> &choices, vector<bool> &selected, vector<vector<int>> &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.size() == choices.size()) {
|
||||
res.push_back(state);
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
// Iterate over all choices
|
||||
unordered_set<int> duplicated;
|
||||
for (int i = 0; i < choices.size(); i++) {
|
||||
int choice = choices[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.find(choice) == duplicated.end()) {
|
||||
// Attempt: make choice, update state
|
||||
duplicated.emplace(choice); // Record the selected element value
|
||||
// Try: make a choice and update the state
|
||||
duplicated.emplace(choice); // Record the chosen value
|
||||
selected[i] = true;
|
||||
state.push_back(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_back();
|
||||
}
|
||||
@@ -41,7 +41,7 @@ vector<vector<int>> permutationsII(vector<int> nums) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
vector<int> nums = {1, 1, 2};
|
||||
|
||||
|
||||
@@ -8,23 +8,23 @@
|
||||
|
||||
vector<TreeNode *> res;
|
||||
|
||||
/* Preorder traversal: Example 1 */
|
||||
/* Preorder traversal: example 1 */
|
||||
void preOrder(TreeNode *root) {
|
||||
if (root == nullptr) {
|
||||
return;
|
||||
}
|
||||
if (root->val == 7) {
|
||||
// Record solution
|
||||
// Record the solution
|
||||
res.push_back(root);
|
||||
}
|
||||
preOrder(root->left);
|
||||
preOrder(root->right);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
TreeNode *root = vectorToTree(vector<int>{1, 7, 3, 4, 5, 6, 7});
|
||||
cout << "\nInitialize binary tree" << endl;
|
||||
cout << "\nInitialize the binary tree" << endl;
|
||||
printTree(root);
|
||||
|
||||
// Preorder traversal
|
||||
|
||||
@@ -9,15 +9,15 @@
|
||||
vector<TreeNode *> path;
|
||||
vector<vector<TreeNode *>> res;
|
||||
|
||||
/* Preorder traversal: Example 2 */
|
||||
/* Preorder traversal: example 2 */
|
||||
void preOrder(TreeNode *root) {
|
||||
if (root == nullptr) {
|
||||
return;
|
||||
}
|
||||
// Attempt
|
||||
// Try
|
||||
path.push_back(root);
|
||||
if (root->val == 7) {
|
||||
// Record solution
|
||||
// Record the solution
|
||||
res.push_back(path);
|
||||
}
|
||||
preOrder(root->left);
|
||||
@@ -26,16 +26,16 @@ void preOrder(TreeNode *root) {
|
||||
path.pop_back();
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
TreeNode *root = vectorToTree(vector<int>{1, 7, 3, 4, 5, 6, 7});
|
||||
cout << "\nInitialize binary tree" << endl;
|
||||
cout << "\nInitialize the binary tree" << endl;
|
||||
printTree(root);
|
||||
|
||||
// Preorder traversal
|
||||
preOrder(root);
|
||||
|
||||
cout << "\nOutput all paths from root node to node 7" << endl;
|
||||
cout << "\nOutput all paths from the root to nodes with value 7" << endl;
|
||||
for (vector<TreeNode *> &path : res) {
|
||||
vector<int> vals;
|
||||
for (TreeNode *node : path) {
|
||||
|
||||
@@ -9,16 +9,16 @@
|
||||
vector<TreeNode *> path;
|
||||
vector<vector<TreeNode *>> res;
|
||||
|
||||
/* Preorder traversal: Example 3 */
|
||||
/* Preorder traversal: example 3 */
|
||||
void preOrder(TreeNode *root) {
|
||||
// Pruning
|
||||
// Prune
|
||||
if (root == nullptr || root->val == 3) {
|
||||
return;
|
||||
}
|
||||
// Attempt
|
||||
// Try
|
||||
path.push_back(root);
|
||||
if (root->val == 7) {
|
||||
// Record solution
|
||||
// Record the solution
|
||||
res.push_back(path);
|
||||
}
|
||||
preOrder(root->left);
|
||||
@@ -27,16 +27,16 @@ void preOrder(TreeNode *root) {
|
||||
path.pop_back();
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
TreeNode *root = vectorToTree(vector<int>{1, 7, 3, 4, 5, 6, 7});
|
||||
cout << "\nInitialize binary tree" << endl;
|
||||
cout << "\nInitialize the binary tree" << endl;
|
||||
printTree(root);
|
||||
|
||||
// Preorder traversal
|
||||
preOrder(root);
|
||||
|
||||
cout << "\nOutput all paths from root node to node 7, requiring paths do not include nodes with value 3" << endl;
|
||||
cout << "\nOutput all paths from the root to nodes with value 7, requiring that no node on the path has value 3" << endl;
|
||||
for (vector<TreeNode *> &path : res) {
|
||||
vector<int> vals;
|
||||
for (TreeNode *node : path) {
|
||||
|
||||
@@ -6,57 +6,57 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Check if the current state is a solution */
|
||||
/* Check whether the current state is a solution */
|
||||
bool isSolution(vector<TreeNode *> &state) {
|
||||
return !state.empty() && state.back()->val == 7;
|
||||
}
|
||||
|
||||
/* Record solution */
|
||||
/* Record the solution */
|
||||
void recordSolution(vector<TreeNode *> &state, vector<vector<TreeNode *>> &res) {
|
||||
res.push_back(state);
|
||||
}
|
||||
|
||||
/* Check if the choice is valid under the current state */
|
||||
/* Check whether the choice is valid in the current state */
|
||||
bool isValid(vector<TreeNode *> &state, TreeNode *choice) {
|
||||
return choice != nullptr && choice->val != 3;
|
||||
}
|
||||
|
||||
/* Update state */
|
||||
/* Update the state */
|
||||
void makeChoice(vector<TreeNode *> &state, TreeNode *choice) {
|
||||
state.push_back(choice);
|
||||
}
|
||||
|
||||
/* Restore state */
|
||||
/* Restore the state */
|
||||
void undoChoice(vector<TreeNode *> &state, TreeNode *choice) {
|
||||
state.pop_back();
|
||||
}
|
||||
|
||||
/* Backtracking algorithm: Example 3 */
|
||||
/* Backtracking: example 3 */
|
||||
void backtrack(vector<TreeNode *> &state, vector<TreeNode *> &choices, vector<vector<TreeNode *>> &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 (TreeNode *choice : 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
|
||||
vector<TreeNode *> nextChoices{choice->left, choice->right};
|
||||
backtrack(state, nextChoices, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
undoChoice(state, choice);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
TreeNode *root = vectorToTree(vector<int>{1, 7, 3, 4, 5, 6, 7});
|
||||
cout << "\nInitialize binary tree" << endl;
|
||||
cout << "\nInitialize the binary tree" << endl;
|
||||
printTree(root);
|
||||
|
||||
// Backtracking algorithm
|
||||
@@ -65,7 +65,7 @@ int main() {
|
||||
vector<vector<TreeNode *>> res;
|
||||
backtrack(state, choices, res);
|
||||
|
||||
cout << "\nOutput all paths from root node to node 7, requiring paths do not include nodes with value 3" << endl;
|
||||
cout << "\nOutput all paths from the root to nodes with value 7, requiring that no node on the path has value 3" << endl;
|
||||
for (vector<TreeNode *> &path : res) {
|
||||
vector<int> vals;
|
||||
for (TreeNode *node : path) {
|
||||
|
||||
@@ -6,26 +6,26 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Backtracking algorithm: Subset sum I */
|
||||
/* Backtracking: subset sum I */
|
||||
void backtrack(vector<int> &state, int target, vector<int> &choices, int start, vector<vector<int>> &res) {
|
||||
// When the subset sum equals target, record the solution
|
||||
// Record a solution when the remaining target reaches 0
|
||||
if (target == 0) {
|
||||
res.push_back(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 (int i = start; i < choices.size(); 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 this choice exceeds the remaining target
|
||||
// The array is sorted, so later elements are at least as large and 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_back(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_back();
|
||||
}
|
||||
}
|
||||
@@ -34,13 +34,13 @@ void backtrack(vector<int> &state, int target, vector<int> &choices, int start,
|
||||
vector<vector<int>> subsetSumI(vector<int> &nums, int target) {
|
||||
vector<int> state; // State (subset)
|
||||
sort(nums.begin(), nums.end()); // Sort nums
|
||||
int start = 0; // Start point for traversal
|
||||
vector<vector<int>> res; // Result list (subset list)
|
||||
int start = 0; // Starting index for iteration
|
||||
vector<vector<int>> res; // Result list (list of subsets)
|
||||
backtrack(state, target, nums, start, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
vector<int> nums = {3, 4, 5};
|
||||
int target = 9;
|
||||
@@ -50,7 +50,7 @@ int main() {
|
||||
cout << "Input array nums = ";
|
||||
printVector(nums);
|
||||
cout << "target = " << target << endl;
|
||||
cout << "All subsets with sum equal to " << target << " are res = " << endl;
|
||||
cout << "All subsets with sum " << target << " , res = " << endl;
|
||||
printVectorMatrix(res);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -6,38 +6,38 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Backtracking algorithm: Subset sum I */
|
||||
/* Backtracking: subset sum I */
|
||||
void backtrack(vector<int> &state, int target, int total, vector<int> &choices, vector<vector<int>> &res) {
|
||||
// When the subset sum equals target, record the solution
|
||||
// Record a solution when the subset sum equals target
|
||||
if (total == target) {
|
||||
res.push_back(state);
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
// Iterate over all choices
|
||||
for (size_t i = 0; i < choices.size(); 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_back(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_back();
|
||||
}
|
||||
}
|
||||
|
||||
/* Solve subset sum I (including duplicate subsets) */
|
||||
/* Solve subset sum I (with duplicate subsets) */
|
||||
vector<vector<int>> subsetSumINaive(vector<int> &nums, int target) {
|
||||
vector<int> state; // State (subset)
|
||||
int total = 0; // Subset sum
|
||||
vector<vector<int>> res; // Result list (subset list)
|
||||
vector<vector<int>> res; // Result list (list of subsets)
|
||||
backtrack(state, target, total, nums, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
vector<int> nums = {3, 4, 5};
|
||||
int target = 9;
|
||||
@@ -47,7 +47,7 @@ int main() {
|
||||
cout << "Input array nums = ";
|
||||
printVector(nums);
|
||||
cout << "target = " << target << endl;
|
||||
cout << "All subsets with sum equal to " << target << " are res = " << endl;
|
||||
cout << "All subsets with sum " << target << " , res = " << endl;
|
||||
printVectorMatrix(res);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -6,31 +6,31 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Backtracking algorithm: Subset sum II */
|
||||
/* Backtracking: subset sum II */
|
||||
void backtrack(vector<int> &state, int target, vector<int> &choices, int start, vector<vector<int>> &res) {
|
||||
// When the subset sum equals target, record the solution
|
||||
// Record a solution when the remaining target reaches 0
|
||||
if (target == 0) {
|
||||
res.push_back(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: iterate from start to avoid choosing the same element again
|
||||
for (int i = start; i < choices.size(); 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 this choice exceeds the remaining target
|
||||
// The array is sorted, so later elements are at least as large and 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_back(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_back();
|
||||
}
|
||||
}
|
||||
@@ -39,13 +39,13 @@ void backtrack(vector<int> &state, int target, vector<int> &choices, int start,
|
||||
vector<vector<int>> subsetSumII(vector<int> &nums, int target) {
|
||||
vector<int> state; // State (subset)
|
||||
sort(nums.begin(), nums.end()); // Sort nums
|
||||
int start = 0; // Start point for traversal
|
||||
vector<vector<int>> res; // Result list (subset list)
|
||||
int start = 0; // Starting index for iteration
|
||||
vector<vector<int>> res; // Result list (list of subsets)
|
||||
backtrack(state, target, nums, start, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
vector<int> nums = {4, 4, 5};
|
||||
int target = 9;
|
||||
@@ -55,7 +55,7 @@ int main() {
|
||||
cout << "Input array nums = ";
|
||||
printVector(nums);
|
||||
cout << "target = " << target << endl;
|
||||
cout << "All subsets with sum equal to " << target << " are res = " << endl;
|
||||
cout << "All subsets with sum " << target << " , res = " << endl;
|
||||
printVectorMatrix(res);
|
||||
|
||||
return 0;
|
||||
|
||||
Reference in New Issue
Block a user