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:
Yudong Jin
2025-12-31 07:44:52 +08:00
committed by GitHub
parent 45e1295241
commit 2778a6f9c7
1284 changed files with 71557 additions and 3275 deletions
@@ -6,18 +6,18 @@
#include "../utils/common.hpp"
/* Random access to elements */
/* Random access to element */
int randomAccess(int *nums, int size) {
// Randomly select a number in the range [0, size)
// Randomly select a number from interval [0, size)
int randomIndex = rand() % size;
// Retrieve and return a random element
// Retrieve and return the random element
int randomNum = nums[randomIndex];
return randomNum;
}
/* Extend array length */
int *extend(int *nums, int size, int enlarge) {
// Initialize an extended length array
// Initialize an array with extended length
int *res = new int[size + enlarge];
// Copy all elements from the original array to the new array
for (int i = 0; i < size; i++) {
@@ -25,23 +25,23 @@ int *extend(int *nums, int size, int enlarge) {
}
// Free memory
delete[] nums;
// Return the new array after expansion
// Return the extended new array
return res;
}
/* Insert element num at `index` */
/* Insert element num at index index in the array */
void insert(int *nums, int size, int num, int index) {
// Move all elements after `index` one position backward
// Move all elements at and after index index backward by one position
for (int i = size - 1; i > index; i--) {
nums[i] = nums[i - 1];
}
// Assign num to the element at index
// Assign num to the element at index index
nums[index] = num;
}
/* Remove the element at `index` */
/* Remove the element at index index */
void remove(int *nums, int size, int index) {
// Move all elements after `index` one position forward
// Move all elements after index index forward by one position
for (int i = index; i < size - 1; i++) {
nums[i] = nums[i + 1];
}
@@ -56,7 +56,7 @@ void traverse(int *nums, int size) {
}
}
/* Search for a specified element in the array */
/* Find the specified element in the array */
int find(int *nums, int size, int target) {
for (int i = 0; i < size; i++) {
if (nums[i] == target)
@@ -67,7 +67,7 @@ int find(int *nums, int size, int target) {
/* Driver Code */
int main() {
/* Initialize an array */
/* Initialize array */
int size = 5;
int *arr = new int[size];
cout << "Array arr = ";
@@ -77,33 +77,33 @@ int main() {
cout << "Array nums = ";
printArray(nums, size);
/* Random access */
/* Insert element */
int randomNum = randomAccess(nums, size);
cout << "Get a random element from nums = " << randomNum << endl;
cout << "Get random element in nums " << randomNum << endl;
/* Length extension */
/* Traverse array */
int enlarge = 3;
nums = extend(nums, size, enlarge);
size += enlarge;
cout << "Extend the array length to 8, resulting in nums = ";
cout << "Extend array length to 8, resulting in nums = ";
printArray(nums, size);
/* Insert element */
insert(nums, size, 6, 3);
cout << "Insert the number 6 at index 3, resulting in nums = ";
cout << "Insert number 6 at index 3, resulting in nums = ";
printArray(nums, size);
/* Remove element */
remove(nums, size, 2);
cout << "Remove the element at index 2, resulting in nums = ";
cout << "Remove element at index 2, resulting in nums = ";
printArray(nums, size);
/* Traverse array */
traverse(nums, size);
/* Search for elements */
/* Find element */
int index = find(nums, size, 3);
cout << "Find element 3 in nums, index = " << index << endl;
cout << "Find element 3 in nums, get index = " << index << endl;
// Free memory
delete[] arr;
@@ -25,7 +25,7 @@ void remove(ListNode *n0) {
delete P;
}
/* Access the node at `index` in the linked list */
/* Access the node at index index in the linked list */
ListNode *access(ListNode *head, int index) {
for (int i = 0; i < index; i++) {
if (head == nullptr)
@@ -35,7 +35,7 @@ ListNode *access(ListNode *head, int index) {
return head;
}
/* Search for the first node with value target in the linked list */
/* Find the first node with value target in the linked list */
int find(ListNode *head, int target) {
int index = 0;
while (head != nullptr) {
@@ -61,26 +61,26 @@ int main() {
n1->next = n2;
n2->next = n3;
n3->next = n4;
cout << "The initialized linked list is" << endl;
cout << "Initialized linked list is" << endl;
printLinkedList(n0);
/* Insert node */
insert(n0, new ListNode(0));
cout << "Linked list after inserting the node is" << endl;
cout << "Linked list after inserting node is" << endl;
printLinkedList(n0);
/* Remove node */
remove(n0);
cout << "Linked list after removing the node is" << endl;
cout << "Linked list after removing node is" << endl;
printLinkedList(n0);
/* Access node */
ListNode *node = access(n0, 3);
cout << "The value of the node at index 3 in the linked list = " << node->val << endl;
cout << "Value of node at index 3 in linked list = " << node->val << endl;
/* Search node */
int index = find(n0, 2);
cout << "The index of the node with value 2 in the linked list = " << index << endl;
cout << "Index of node with value 2 in linked list = " << index << endl;
// Free memory
freeMemoryLinkedList(n0);
@@ -13,21 +13,21 @@ int main() {
cout << "List nums = ";
printVector(nums);
/* Access element */
int num = nums[1];
cout << "Access the element at index 1, obtained num = " << num << endl;
/* Update element */
int num = nums[1];
cout << "Access element at index 1, get num = " << num << endl;
/* Add elements at the end */
nums[1] = 0;
cout << "Update the element at index 1 to 0, resulting in nums = ";
cout << "Update element at index 1 to 0, resulting in nums = ";
printVector(nums);
/* Clear list */
/* Remove element */
nums.clear();
cout << "After clearing the list, nums = ";
cout << "After clearing list, nums = ";
printVector(nums);
/* Add element at the end */
/* Direct traversal of list elements */
nums.push_back(1);
nums.push_back(3);
nums.push_back(2);
@@ -36,22 +36,22 @@ int main() {
cout << "After adding elements, nums = ";
printVector(nums);
/* Insert element in the middle */
/* Sort list */
nums.insert(nums.begin() + 3, 6);
cout << "Insert the number 6 at index 3, resulting in nums = ";
cout << "Insert number 6 at index 3, resulting in nums = ";
printVector(nums);
/* Remove element */
nums.erase(nums.begin() + 3);
cout << "Remove the element at index 3, resulting in nums = ";
cout << "Remove element at index 3, resulting in nums = ";
printVector(nums);
/* Traverse the list by index */
/* Traverse list by index */
int count = 0;
for (int i = 0; i < nums.size(); i++) {
count += nums[i];
}
/* Traverse the list elements */
/* Directly traverse list elements */
count = 0;
for (int x : nums) {
count += x;
@@ -65,7 +65,7 @@ int main() {
/* Sort list */
sort(nums.begin(), nums.end());
cout << "After sorting the list, nums = ";
cout << "After sorting list, nums = ";
printVector(nums);
return 0;
@@ -12,7 +12,7 @@ class MyList {
int *arr; // Array (stores list elements)
int arrCapacity = 10; // List capacity
int arrSize = 0; // List length (current number of elements)
int extendRatio = 2; // Multiple for each list expansion
int extendRatio = 2; // Multiple by which the list capacity is extended each time
public:
/* Constructor */
@@ -35,7 +35,7 @@ class MyList {
return arrCapacity;
}
/* Access element */
/* Update element */
int get(int index) {
// If the index is out of bounds, throw an exception, as below
if (index < 0 || index >= size())
@@ -43,16 +43,16 @@ class MyList {
return arr[index];
}
/* Update element */
/* Add elements at the end */
void set(int index, int num) {
if (index < 0 || index >= size())
throw out_of_range("Index out of bounds");
arr[index] = num;
}
/* Add element at the end */
/* Direct traversal of list elements */
void add(int num) {
// When the number of elements exceeds capacity, trigger the expansion mechanism
// When the number of elements exceeds capacity, trigger the extension mechanism
if (size() == capacity())
extendCapacity();
arr[size()] = num;
@@ -60,14 +60,14 @@ class MyList {
arrSize++;
}
/* Insert element in the middle */
/* Sort list */
void insert(int index, int num) {
if (index < 0 || index >= size())
throw out_of_range("Index out of bounds");
// When the number of elements exceeds capacity, trigger the expansion mechanism
// When the number of elements exceeds capacity, trigger the extension mechanism
if (size() == capacity())
extendCapacity();
// Move all elements after `index` one position backward
// Move all elements after index index forward by one position
for (int j = size() - 1; j >= index; j--) {
arr[j + 1] = arr[j];
}
@@ -81,7 +81,7 @@ class MyList {
if (index < 0 || index >= size())
throw out_of_range("Index out of bounds");
int num = arr[index];
// Move all elements after `index` one position forward
// Create a new array with length _extend_ratio times the original array, and copy the original array to the new array
for (int j = index; j < size() - 1; j++) {
arr[j] = arr[j + 1];
}
@@ -91,9 +91,9 @@ class MyList {
return num;
}
/* Extend list */
/* Driver Code */
void extendCapacity() {
// Create a new array with a length multiple of the original array by extendRatio
// Create a new array with length extendRatio times the original array
int newCapacity = capacity() * extendRatio;
int *tmp = arr;
arr = new int[newCapacity];
@@ -106,9 +106,9 @@ class MyList {
arrCapacity = newCapacity;
}
/* Convert the list to a Vector for printing */
/* Convert list to Vector for printing */
vector<int> toVector() {
// Only convert elements within valid length range
// Elements enqueue
vector<int> vec(size());
for (int i = 0; i < size(); i++) {
vec[i] = arr[i];
@@ -121,7 +121,7 @@ class MyList {
int main() {
/* Initialize list */
MyList *nums = new MyList();
/* Add element at the end */
/* Direct traversal of list elements */
nums->add(1);
nums->add(3);
nums->add(2);
@@ -132,34 +132,34 @@ int main() {
printVector(vec);
cout << "Capacity = " << nums->capacity() << ", length = " << nums->size() << endl;
/* Insert element in the middle */
/* Sort list */
nums->insert(3, 6);
cout << "Insert the number 6 at index 3, resulting in nums = ";
cout << "Insert number 6 at index 3, resulting in nums = ";
vec = nums->toVector();
printVector(vec);
/* Remove element */
nums->remove(3);
cout << "Remove the element at index 3, resulting in nums = ";
cout << "Remove element at index 3, resulting in nums = ";
vec = nums->toVector();
printVector(vec);
/* Access element */
int num = nums->get(1);
cout << "Access the element at index 1, obtained num = " << num << endl;
/* Update element */
int num = nums->get(1);
cout << "Access element at index 1, get num = " << num << endl;
/* Add elements at the end */
nums->set(1, 0);
cout << "Update the element at index 1 to 0, resulting in nums = ";
cout << "Update element at index 1 to 0, resulting in nums = ";
vec = nums->toVector();
printVector(vec);
/* Test expansion mechanism */
/* Test capacity expansion mechanism */
for (int i = 0; i < 10; i++) {
// At i = 5, the list length will exceed the list capacity, triggering the expansion mechanism at this time
// At i = 5, the list length will exceed the list capacity, triggering the expansion mechanism
nums->add(i);
}
cout << "After extending, list nums = ";
cout << "List nums after expansion = ";
vec = nums->toVector();
printVector(vec);
cout << "Capacity = " << nums->capacity() << ", length = " << nums->size() << endl;
+12 -12
View File
@@ -6,7 +6,7 @@
#include "../utils/common.hpp"
/* Backtracking algorithm: n queens */
/* Backtracking algorithm: 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
@@ -16,30 +16,30 @@ void backtrack(int row, int n, vector<vector<string>> &state, vector<vector<vect
}
// Traverse all columns
for (int col = 0; col < n; col++) {
// Calculate the main and minor diagonals corresponding to the cell
// Calculate the main diagonal and anti-diagonal corresponding to this cell
int diag1 = row - col + n - 1;
int diag2 = row + col;
// Pruning: do not allow queens on the column, main diagonal, or minor diagonal of the cell
// Pruning: do not allow queens to exist in the column, main diagonal, and anti-diagonal of this cell
if (!cols[col] && !diags1[diag1] && !diags2[diag2]) {
// Attempt: place the queen in the cell
// Attempt: place the queen in this cell
state[row][col] = "Q";
cols[col] = diags1[diag1] = diags2[diag2] = true;
// Place the next row
backtrack(row + 1, n, state, res, cols, diags1, diags2);
// Retract: restore the cell to an empty spot
// Backtrack: restore this cell to an empty cell
state[row][col] = "#";
cols[col] = diags1[diag1] = diags2[diag2] = false;
}
}
}
/* Solve n queens */
/* Solve N queens */
vector<vector<vector<string>>> nQueens(int n) {
// Initialize an n*n size chessboard, where 'Q' represents the queen and '#' represents an empty spot
// Initialize an n*n chessboard, where 'Q' represents a queen and '#' represents an empty cell
vector<vector<string>> state(n, vector<string>(n, "#"));
vector<bool> cols(n, false); // Record columns with queens
vector<bool> diags1(2 * n - 1, false); // Record main diagonals with queens
vector<bool> diags2(2 * n - 1, false); // Record minor diagonals with queens
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<vector<vector<string>>> res;
backtrack(0, n, state, res, cols, diags1, diags2);
@@ -52,8 +52,8 @@ int main() {
int n = 4;
vector<vector<vector<string>>> res = nQueens(n);
cout << "Input the dimensions of the chessboard as " << n << endl;
cout << "Total number of queen placement solutions = " << res.size() << endl;
cout << "Input board size is " << n << endl;
cout << "Total queen placement solutions: " << res.size() << endl;
for (const vector<vector<string>> &state : res) {
cout << "--------------------" << endl;
for (const vector<string> &row : state) {
@@ -6,7 +6,7 @@
#include "../utils/common.hpp"
/* Backtracking algorithm: Permutation I */
/* Backtracking algorithm: 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
if (state.size() == choices.size()) {
@@ -18,19 +18,19 @@ void backtrack(vector<int> &state, const vector<int> &choices, vector<bool> &sel
int choice = choices[i];
// Pruning: do not allow repeated selection of elements
if (!selected[i]) {
// Attempt: make a choice, update the state
// Attempt: make choice, update state
selected[i] = true;
state.push_back(choice);
// Proceed to the next round of selection
backtrack(state, choices, selected, res);
// Retract: undo the choice, restore to the previous state
// Backtrack: undo choice, restore to previous state
selected[i] = false;
state.pop_back();
}
}
}
/* Permutation I */
/* Permutations I */
vector<vector<int>> permutationsI(vector<int> nums) {
vector<int> state;
vector<bool> selected(nums.size(), false);
@@ -6,7 +6,7 @@
#include "../utils/common.hpp"
/* Backtracking algorithm: Permutation II */
/* Backtracking algorithm: 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
if (state.size() == choices.size()) {
@@ -19,20 +19,20 @@ void backtrack(vector<int> &state, const vector<int> &choices, vector<bool> &sel
int choice = choices[i];
// Pruning: do not allow repeated selection of elements and do not allow repeated selection of equal elements
if (!selected[i] && duplicated.find(choice) == duplicated.end()) {
// Attempt: make a choice, update the state
duplicated.emplace(choice); // Record selected element values
// Attempt: make choice, update state
duplicated.emplace(choice); // Record the selected element value
selected[i] = true;
state.push_back(choice);
// Proceed to the next round of selection
backtrack(state, choices, selected, res);
// Retract: undo the choice, restore to the previous state
// Backtrack: undo choice, restore to previous state
selected[i] = false;
state.pop_back();
}
}
}
/* Permutation II */
/* Permutations II */
vector<vector<int>> permutationsII(vector<int> nums) {
vector<int> state;
vector<bool> selected(nums.size(), false);
@@ -8,7 +8,7 @@
vector<TreeNode *> res;
/* Pre-order traversal: Example one */
/* Preorder traversal: Example 1 */
void preOrder(TreeNode *root) {
if (root == nullptr) {
return;
@@ -27,7 +27,7 @@ int main() {
cout << "\nInitialize binary tree" << endl;
printTree(root);
// Pre-order traversal
// Preorder traversal
preOrder(root);
cout << "\nOutput all nodes with value 7" << endl;
@@ -9,7 +9,7 @@
vector<TreeNode *> path;
vector<vector<TreeNode *>> res;
/* Pre-order traversal: Example two */
/* Preorder traversal: Example 2 */
void preOrder(TreeNode *root) {
if (root == nullptr) {
return;
@@ -22,7 +22,7 @@ void preOrder(TreeNode *root) {
}
preOrder(root->left);
preOrder(root->right);
// Retract
// Backtrack
path.pop_back();
}
@@ -32,10 +32,10 @@ int main() {
cout << "\nInitialize binary tree" << endl;
printTree(root);
// Pre-order traversal
// Preorder traversal
preOrder(root);
cout << "\nOutput all root-to-node 7 paths" << endl;
cout << "\nOutput all paths from root node to node 7" << endl;
for (vector<TreeNode *> &path : res) {
vector<int> vals;
for (TreeNode *node : path) {
@@ -9,7 +9,7 @@
vector<TreeNode *> path;
vector<vector<TreeNode *>> res;
/* Pre-order traversal: Example three */
/* Preorder traversal: Example 3 */
void preOrder(TreeNode *root) {
// Pruning
if (root == nullptr || root->val == 3) {
@@ -23,7 +23,7 @@ void preOrder(TreeNode *root) {
}
preOrder(root->left);
preOrder(root->right);
// Retract
// Backtrack
path.pop_back();
}
@@ -33,10 +33,10 @@ int main() {
cout << "\nInitialize binary tree" << endl;
printTree(root);
// Pre-order traversal
// Preorder traversal
preOrder(root);
cout << "\nOutput all root-to-node 7 paths, requiring paths not to include nodes with value 3" << endl;
cout << "\nOutput all paths from root node to node 7, requiring paths do not include nodes with value 3" << endl;
for (vector<TreeNode *> &path : res) {
vector<int> vals;
for (TreeNode *node : path) {
@@ -6,7 +6,7 @@
#include "../utils/common.hpp"
/* Determine if the current state is a solution */
/* Check if the current state is a solution */
bool isSolution(vector<TreeNode *> &state) {
return !state.empty() && state.back()->val == 7;
}
@@ -16,7 +16,7 @@ void recordSolution(vector<TreeNode *> &state, vector<vector<TreeNode *>> &res)
res.push_back(state);
}
/* Determine if the choice is legal under the current state */
/* Check if the choice is valid under the current state */
bool isValid(vector<TreeNode *> &state, TreeNode *choice) {
return choice != nullptr && choice->val != 3;
}
@@ -31,23 +31,23 @@ void undoChoice(vector<TreeNode *> &state, TreeNode *choice) {
state.pop_back();
}
/* Backtracking algorithm: Example three */
/* Backtracking algorithm: Example 3 */
void backtrack(vector<TreeNode *> &state, vector<TreeNode *> &choices, vector<vector<TreeNode *>> &res) {
// Check if it's a solution
// Check if it is a solution
if (isSolution(state)) {
// Record solution
recordSolution(state, res);
}
// Traverse all choices
for (TreeNode *choice : choices) {
// Pruning: check if the choice is legal
// Pruning: check if the choice is valid
if (isValid(state, choice)) {
// Attempt: make a choice, update the state
// Attempt: make choice, update state
makeChoice(state, choice);
// Proceed to the next round of selection
vector<TreeNode *> nextChoices{choice->left, choice->right};
backtrack(state, nextChoices, res);
// Retract: undo the choice, restore to the previous state
// Backtrack: undo choice, restore to previous state
undoChoice(state, choice);
}
}
@@ -65,7 +65,7 @@ int main() {
vector<vector<TreeNode *>> res;
backtrack(state, choices, res);
cout << "\nOutput all root-to-node 7 paths, requiring paths not to include nodes with value 3" << endl;
cout << "\nOutput all paths from root node to node 7, requiring paths do not include nodes with value 3" << endl;
for (vector<TreeNode *> &path : res) {
vector<int> vals;
for (TreeNode *node : path) {
@@ -6,7 +6,7 @@
#include "../utils/common.hpp"
/* Backtracking algorithm: Subset Sum I */
/* Backtracking algorithm: 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
if (target == 0) {
@@ -14,23 +14,23 @@ void backtrack(vector<int> &state, int target, vector<int> &choices, int start,
return;
}
// Traverse all choices
// Pruning two: start traversing from start to avoid generating duplicate subsets
// Pruning 2: start traversing from start to avoid generating duplicate subsets
for (int i = start; i < choices.size(); i++) {
// Pruning one: if the subset sum exceeds target, end the loop immediately
// 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
if (target - choices[i] < 0) {
break;
}
// Attempt: make a choice, update target, start
// Attempt: make choice, update target, start
state.push_back(choices[i]);
// Proceed to the next round of selection
backtrack(state, target - choices[i], choices, i, res);
// Retract: undo the choice, restore to the previous state
// Backtrack: undo choice, restore to previous state
state.pop_back();
}
}
/* Solve Subset Sum I */
/* Solve subset sum I */
vector<vector<int>> subsetSumI(vector<int> &nums, int target) {
vector<int> state; // State (subset)
sort(nums.begin(), nums.end()); // Sort nums
@@ -50,7 +50,7 @@ int main() {
cout << "Input array nums = ";
printVector(nums);
cout << "target = " << target << endl;
cout << "All subsets summing to " << target << "is" << endl;
cout << "All subsets with sum equal to " << target << " are res = " << endl;
printVectorMatrix(res);
return 0;
@@ -6,7 +6,7 @@
#include "../utils/common.hpp"
/* Backtracking algorithm: Subset Sum I */
/* Backtracking algorithm: 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
if (total == target) {
@@ -15,20 +15,20 @@ void backtrack(vector<int> &state, int target, int total, vector<int> &choices,
}
// Traverse all choices
for (size_t i = 0; i < choices.size(); i++) {
// Pruning: if the subset sum exceeds target, skip that choice
// Pruning: if the subset sum exceeds target, skip this choice
if (total + choices[i] > target) {
continue;
}
// Attempt: make a choice, update elements and total
// Attempt: make choice, update element sum total
state.push_back(choices[i]);
// Proceed to the next round of selection
backtrack(state, target, total + choices[i], choices, res);
// Retract: undo the choice, restore to the previous state
// Backtrack: undo choice, restore to previous state
state.pop_back();
}
}
/* Solve Subset Sum I (including duplicate subsets) */
/* Solve subset sum I (including duplicate subsets) */
vector<vector<int>> subsetSumINaive(vector<int> &nums, int target) {
vector<int> state; // State (subset)
int total = 0; // Subset sum
@@ -47,7 +47,7 @@ int main() {
cout << "Input array nums = ";
printVector(nums);
cout << "target = " << target << endl;
cout << "All subsets summing to " << target << "is" << endl;
cout << "All subsets with sum equal to " << target << " are res = " << endl;
printVectorMatrix(res);
return 0;
@@ -6,7 +6,7 @@
#include "../utils/common.hpp"
/* Backtracking algorithm: Subset Sum II */
/* Backtracking algorithm: 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
if (target == 0) {
@@ -14,28 +14,28 @@ void backtrack(vector<int> &state, int target, vector<int> &choices, int start,
return;
}
// Traverse all choices
// Pruning two: start traversing from start to avoid generating duplicate subsets
// Pruning three: start traversing from start to avoid repeatedly selecting the same element
// Pruning 2: start traversing from start to avoid generating duplicate subsets
// Pruning 3: start traversing from start to avoid repeatedly selecting the same element
for (int i = start; i < choices.size(); i++) {
// Pruning one: if the subset sum exceeds target, end the loop immediately
// 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
if (target - choices[i] < 0) {
break;
}
// Pruning four: if the element equals the left element, it indicates that the search branch is repeated, skip it
// Pruning 4: if this element equals the left element, it means this search branch is duplicate, skip it directly
if (i > start && choices[i] == choices[i - 1]) {
continue;
}
// Attempt: make a choice, update target, start
// Attempt: make choice, update target, start
state.push_back(choices[i]);
// Proceed to the next round of selection
backtrack(state, target - choices[i], choices, i + 1, res);
// Retract: undo the choice, restore to the previous state
// Backtrack: undo choice, restore to previous state
state.pop_back();
}
}
/* Solve Subset Sum II */
/* Solve subset sum II */
vector<vector<int>> subsetSumII(vector<int> &nums, int target) {
vector<int> state; // State (subset)
sort(nums.begin(), nums.end()); // Sort nums
@@ -55,7 +55,7 @@ int main() {
cout << "Input array nums = ";
printVector(nums);
cout << "target = " << target << endl;
cout << "All subsets summing to " << target << "is" << endl;
cout << "All subsets with sum equal to " << target << " are res = " << endl;
printVectorMatrix(res);
return 0;
@@ -9,7 +9,7 @@
/* for loop */
int forLoop(int n) {
int res = 0;
// Loop sum 1, 2, ..., n-1, n
// Sum 1, 2, ..., n-1, n
for (int i = 1; i <= n; ++i) {
res += i;
}
@@ -20,7 +20,7 @@ int forLoop(int n) {
int whileLoop(int n) {
int res = 0;
int i = 1; // Initialize condition variable
// Loop sum 1, 2, ..., n-1, n
// Sum 1, 2, ..., n-1, n
while (i <= n) {
res += i;
i++; // Update condition variable
@@ -32,7 +32,7 @@ int whileLoop(int n) {
int whileLoopII(int n) {
int res = 0;
int i = 1; // Initialize condition variable
// Loop sum 1, 4, 10, ...
// Sum 1, 4, 10, ...
while (i <= n) {
res += i;
// Update condition variable
@@ -42,7 +42,7 @@ int whileLoopII(int n) {
return res;
}
/* Double for loop */
/* Nested for loop */
string nestedForLoop(int n) {
ostringstream res;
// Loop i = 1, 2, ..., n-1, n
@@ -61,16 +61,16 @@ int main() {
int res;
res = forLoop(n);
cout << "\nSum result of the for loop res = " << res << endl;
cout << "\nfor loop sum result res = " << res << endl;
res = whileLoop(n);
cout << "\nSum result of the while loop res = " << res << endl;
cout << "\nwhile loop sum result res = " << res << endl;
res = whileLoopII(n);
cout << "\nSum result of the while loop (with two updates) res = " << res << endl;
cout << "\nwhile loop (two updates) sum result res = " << res << endl;
string resStr = nestedForLoop(n);
cout << "\nResult of the double for loop traversal = " << resStr << endl;
cout << "\nDouble for loop traversal result " << resStr << endl;
return 0;
}
@@ -11,25 +11,25 @@ int recur(int n) {
// Termination condition
if (n == 1)
return 1;
// Recursive: recursive call
// Recurse: recursive call
int res = recur(n - 1);
// Return: return result
return n + res;
}
/* Simulate recursion with iteration */
/* Simulate recursion using iteration */
int forLoopRecur(int n) {
// Use an explicit stack to simulate the system call stack
stack<int> stack;
int res = 0;
// Recursive: recursive call
// Recurse: recursive call
for (int i = n; i > 0; i--) {
// Simulate "recursive" by "pushing onto the stack"
// Simulate "recurse" with "push"
stack.push(i);
}
// Return: return result
while (!stack.empty()) {
// Simulate "return" by "popping from the stack"
// Simulate "return" with "pop"
res += stack.top();
stack.pop();
}
@@ -46,7 +46,7 @@ int tailRecur(int n, int res) {
return tailRecur(n - 1, res + n);
}
/* Fibonacci sequence: Recursion */
/* Fibonacci sequence: recursion */
int fib(int n) {
// Termination condition f(1) = 0, f(2) = 1
if (n == 1 || n == 2)
@@ -63,16 +63,16 @@ int main() {
int res;
res = recur(n);
cout << "\nSum result of the recursive function res = " << res << endl;
cout << "\nRecursive function sum result res = " << res << endl;
res = forLoopRecur(n);
cout << "\nSum result using iteration to simulate recursion res = " << res << endl;
cout << "\nUsing iteration to simulate recursive sum result res = " << res << endl;
res = tailRecur(n, 0);
cout << "\nSum result of the tail-recursive function res = " << res << endl;
cout << "\nTail recursive function sum result res = " << res << endl;
res = fib(n);
cout << "The " << n << "th number in the Fibonacci sequence is " << res << endl;
cout << "\nThe " << n << "th term of the Fibonacci sequence is " << res << endl;
return 0;
}
@@ -12,26 +12,26 @@ int func() {
return 0;
}
/* Constant complexity */
/* Constant order */
void constant(int n) {
// Constants, variables, objects occupy O(1) space
const int a = 0;
int b = 0;
vector<int> nums(10000);
ListNode node(0);
// Variables in a loop occupy O(1) space
// Variables in the loop occupy O(1) space
for (int i = 0; i < n; i++) {
int c = 0;
}
// Functions in a loop occupy O(1) space
// Functions in the loop occupy O(1) space
for (int i = 0; i < n; i++) {
func();
}
}
/* Linear complexity */
/* Linear order */
void linear(int n) {
// Array of length n occupies O(n) space
// Array of length n uses O(n) space
vector<int> nums(n);
// A list of length n occupies O(n) space
vector<ListNode> nodes;
@@ -45,7 +45,7 @@ void linear(int n) {
}
}
/* Linear complexity (recursive implementation) */
/* Linear order (recursive implementation) */
void linearRecur(int n) {
cout << "Recursion n = " << n << endl;
if (n == 1)
@@ -53,9 +53,9 @@ void linearRecur(int n) {
linearRecur(n - 1);
}
/* Quadratic complexity */
/* Exponential order */
void quadratic(int n) {
// A two-dimensional list occupies O(n^2) space
// 2D list uses O(n^2) space
vector<vector<int>> numMatrix;
for (int i = 0; i < n; i++) {
vector<int> tmp;
@@ -66,16 +66,16 @@ void quadratic(int n) {
}
}
/* Quadratic complexity (recursive implementation) */
/* Quadratic order (recursive implementation) */
int quadraticRecur(int n) {
if (n <= 0)
return 0;
vector<int> nums(n);
cout << "Recursive n = " << n << ", length of nums = " << nums.size() << endl;
cout << "In recursion n = " << n << ", nums length = " << nums.size() << endl;
return quadraticRecur(n - 1);
}
/* Exponential complexity (building a full binary tree) */
/* Driver Code */
TreeNode *buildTree(int n) {
if (n == 0)
return nullptr;
@@ -88,15 +88,15 @@ TreeNode *buildTree(int n) {
/* Driver Code */
int main() {
int n = 5;
// Constant complexity
// Constant order
constant(n);
// Linear complexity
// Linear order
linear(n);
linearRecur(n);
// Quadratic complexity
// Exponential order
quadratic(n);
quadraticRecur(n);
// Exponential complexity
// Exponential order
TreeNode *root = buildTree(n);
printTree(root);
@@ -6,7 +6,7 @@
#include "../utils/common.hpp"
/* Constant complexity */
/* Constant order */
int constant(int n) {
int count = 0;
int size = 100000;
@@ -15,7 +15,7 @@ int constant(int n) {
return count;
}
/* Linear complexity */
/* Linear order */
int linear(int n) {
int count = 0;
for (int i = 0; i < n; i++)
@@ -23,20 +23,20 @@ int linear(int n) {
return count;
}
/* Linear complexity (traversing an array) */
/* Linear order (traversing array) */
int arrayTraversal(vector<int> &nums) {
int count = 0;
// Loop count is proportional to the length of the array
// Number of iterations is proportional to the array length
for (int num : nums) {
count++;
}
return count;
}
/* Quadratic complexity */
/* Exponential order */
int quadratic(int n) {
int count = 0;
// Loop count is squared in relation to the data size n
// Number of iterations is quadratically related to the data size n
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
count++;
@@ -45,29 +45,29 @@ int quadratic(int n) {
return count;
}
/* Quadratic complexity (bubble sort) */
/* Quadratic order (bubble sort) */
int bubbleSort(vector<int> &nums) {
int count = 0; // Counter
// Outer loop: unsorted range is [0, i]
for (int i = nums.size() - 1; i > 0; i--) {
// Inner loop: swap the largest element in the unsorted range [0, i] to the right end of the range
// Inner loop: swap the largest element in the unsorted range [0, i] to the rightmost end of that range
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// Swap nums[j] and nums[j + 1]
int tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
count += 3; // Element swap includes 3 individual operations
count += 3; // Element swap includes 3 unit operations
}
}
}
return count;
}
/* Exponential complexity (loop implementation) */
/* Exponential order (loop implementation) */
int exponential(int n) {
int count = 0, base = 1;
// Cells split into two every round, forming the sequence 1, 2, 4, 8, ..., 2^(n-1)
// Cells divide into two every round, forming sequence 1, 2, 4, 8, ..., 2^(n-1)
for (int i = 0; i < n; i++) {
for (int j = 0; j < base; j++) {
count++;
@@ -78,14 +78,14 @@ int exponential(int n) {
return count;
}
/* Exponential complexity (recursive implementation) */
/* Exponential order (recursive implementation) */
int expRecur(int n) {
if (n == 1)
return 1;
return expRecur(n - 1) + expRecur(n - 1) + 1;
}
/* Logarithmic complexity (loop implementation) */
/* Logarithmic order (loop implementation) */
int logarithmic(int n) {
int count = 0;
while (n > 1) {
@@ -95,14 +95,14 @@ int logarithmic(int n) {
return count;
}
/* Logarithmic complexity (recursive implementation) */
/* Logarithmic order (recursive implementation) */
int logRecur(int n) {
if (n <= 1)
return 0;
return logRecur(n / 2) + 1;
}
/* Linear logarithmic complexity */
/* Linearithmic order */
int linearLogRecur(int n) {
if (n <= 1)
return 1;
@@ -113,12 +113,12 @@ int linearLogRecur(int n) {
return count;
}
/* Factorial complexity (recursive implementation) */
/* Factorial order (recursive implementation) */
int factorialRecur(int n) {
if (n == 0)
return 1;
int count = 0;
// From 1 split into n
// Split from 1 into n
for (int i = 0; i < n; i++) {
count += factorialRecur(n - 1);
}
@@ -127,42 +127,42 @@ int factorialRecur(int n) {
/* Driver Code */
int main() {
// Can modify n to experience the trend of operation count changes under various complexities
// You can modify n to run and observe the trend of the number of operations for various complexities
int n = 8;
cout << "Input data size n = " << n << endl;
int count = constant(n);
cout << "Number of constant complexity operations = " << count << endl;
cout << "Constant order operation count = " << count << endl;
count = linear(n);
cout << "Number of linear complexity operations = " << count << endl;
cout << "Linear order operation count = " << count << endl;
vector<int> arr(n);
count = arrayTraversal(arr);
cout << "Number of linear complexity operations (traversing the array) = " << count << endl;
cout << "Linear order (array traversal) operation count = " << count << endl;
count = quadratic(n);
cout << "Number of quadratic order operations = " << count << endl;
cout << "Quadratic order operation count = " << count << endl;
vector<int> nums(n);
for (int i = 0; i < n; i++)
nums[i] = n - i; // [n,n-1,...,2,1]
count = bubbleSort(nums);
cout << "Number of quadratic order operations (bubble sort) = " << count << endl;
cout << "Quadratic order (bubble sort) operation count = " << count << endl;
count = exponential(n);
cout << "Number of exponential complexity operations (implemented by loop) = " << count << endl;
cout << "Exponential order (loop implementation) operation count = " << count << endl;
count = expRecur(n);
cout << "Number of exponential complexity operations (implemented by recursion) = " << count << endl;
cout << "Exponential order (recursive implementation) operation count = " << count << endl;
count = logarithmic(n);
cout << "Number of logarithmic complexity operations (implemented by loop) = " << count << endl;
cout << "Logarithmic order (loop implementation) operation count = " << count << endl;
count = logRecur(n);
cout << "Number of logarithmic complexity operations (implemented by recursion) = " << count << endl;
cout << "Logarithmic order (recursive implementation) operation count = " << count << endl;
count = linearLogRecur(n);
cout << "Number of linear logarithmic complexity operations (implemented by recursion) = " << count << endl;
cout << "Linearithmic order (recursive implementation) operation count = " << count << endl;
count = factorialRecur(n);
cout << "Number of factorial complexity operations (implemented by recursion) = " << count << endl;
cout << "Factorial order (recursive implementation) operation count = " << count << endl;
return 0;
}
@@ -6,14 +6,14 @@
#include "../utils/common.hpp"
/* Generate an array with elements {1, 2, ..., n} in a randomly shuffled order */
/* Generate an array with elements { 1, 2, ..., n }, order shuffled */
vector<int> randomNumbers(int n) {
vector<int> nums(n);
// Generate array nums = { 1, 2, 3, ..., n }
for (int i = 0; i < n; i++) {
nums[i] = i + 1;
}
// Generate a random seed using system time
// Use system time to generate random seed
unsigned seed = chrono::system_clock::now().time_since_epoch().count();
// Randomly shuffle array elements
shuffle(nums.begin(), nums.end(), default_random_engine(seed));
@@ -23,8 +23,8 @@ vector<int> randomNumbers(int n) {
/* Find the index of number 1 in array nums */
int findOne(vector<int> &nums) {
for (int i = 0; i < nums.size(); i++) {
// When element 1 is at the start of the array, achieve best time complexity O(1)
// When element 1 is at the end of the array, achieve worst time complexity O(n)
// When element 1 is at the head of the array, best time complexity O(1) is achieved
// When element 1 is at the tail of the array, worst time complexity O(n) is achieved
if (nums[i] == 1)
return i;
}
@@ -37,9 +37,9 @@ int main() {
int n = 100;
vector<int> nums = randomNumbers(n);
int index = findOne(nums);
cout << "\nThe array [ 1, 2, ..., n ] after being shuffled = ";
cout << "\nArray [ 1, 2, ..., n ] after shuffling = ";
printVector(nums);
cout << "The index of number 1 is " << index << endl;
cout << "Index of number 1 is " << index << endl;
}
return 0;
}
@@ -8,20 +8,20 @@
/* Binary search: problem f(i, j) */
int dfs(vector<int> &nums, int target, int i, int j) {
// If the interval is empty, indicating no target element, return -1
// If the interval is empty, it means there is no target element, return -1
if (i > j) {
return -1;
}
// Calculate midpoint index m
int m = i + (j - i) / 2;
// Calculate the midpoint index m
int m = (i + j) / 2;
if (nums[m] < target) {
// Recursive subproblem f(m+1, j)
// Recursion subproblem f(m+1, j)
return dfs(nums, target, m + 1, j);
} else if (nums[m] > target) {
// Recursive subproblem f(i, m-1)
// Recursion subproblem f(i, m-1)
return dfs(nums, target, i, m - 1);
} else {
// Found the target element, thus return its index
// Found the target element, return its index
return m;
}
}
@@ -29,7 +29,7 @@ int dfs(vector<int> &nums, int target, int i, int j) {
/* Binary search */
int binarySearch(vector<int> &nums, int target) {
int n = nums.size();
// Solve problem f(0, n-1)
// Solve the problem f(0, n-1)
return dfs(nums, target, 0, n - 1);
}
@@ -38,9 +38,9 @@ int main() {
int target = 6;
vector<int> nums = {1, 3, 6, 8, 12, 15, 23, 26, 31, 35};
// Binary search (double closed interval)
// Binary search (closed interval on both sides)
int index = binarySearch(nums, target);
cout << "Index of target element 6 =" << index << endl;
cout << "Index of target element 6 = " << index << endl;
return 0;
}
}
@@ -6,26 +6,26 @@
#include "../utils/common.hpp"
/* Build binary tree: Divide and conquer */
/* Build binary tree: divide and conquer */
TreeNode *dfs(vector<int> &preorder, unordered_map<int, int> &inorderMap, int i, int l, int r) {
// Terminate when subtree interval is empty
// Terminate when the subtree interval is empty
if (r - l < 0)
return NULL;
// Initialize root node
// Initialize the root node
TreeNode *root = new TreeNode(preorder[i]);
// Query m to divide left and right subtrees
// Query m to divide the left and right subtrees
int m = inorderMap[preorder[i]];
// Subproblem: build left subtree
// Subproblem: build the left subtree
root->left = dfs(preorder, inorderMap, i + 1, l, m - 1);
// Subproblem: build right subtree
// Subproblem: build the right subtree
root->right = dfs(preorder, inorderMap, i + 1 + m - l, m + 1, r);
// Return root node
// Return the root node
return root;
}
/* Build binary tree */
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
// Initialize hash table, storing in-order elements to indices mapping
// Initialize hash map, storing the mapping from inorder elements to indices
unordered_map<int, int> inorderMap;
for (int i = 0; i < inorder.size(); i++) {
inorderMap[inorder[i]] = i;
@@ -38,9 +38,9 @@ TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
int main() {
vector<int> preorder = {3, 9, 2, 1, 7};
vector<int> inorder = {9, 3, 1, 2, 7};
cout << "Pre-order traversal = ";
cout << "Preorder traversal = ";
printVector(preorder);
cout << "In-order traversal = ";
cout << "Inorder traversal = ";
printVector(inorder);
TreeNode *root = buildTree(preorder, inorder);
@@ -6,40 +6,40 @@
#include "../utils/common.hpp"
/* Move a disc */
/* Move a disk */
void move(vector<int> &src, vector<int> &tar) {
// Take out a disc from the top of src
// Take out a disk from the top of src
int pan = src.back();
src.pop_back();
// Place the disc on top of tar
// Place the disk on top of tar
tar.push_back(pan);
}
/* Solve the Tower of Hanoi problem f(i) */
void dfs(int i, vector<int> &src, vector<int> &buf, vector<int> &tar) {
// If only one disc remains on src, move it to tar
// If there is only one disk left in src, move it directly to tar
if (i == 1) {
move(src, tar);
return;
}
// Subproblem f(i-1): move the top i-1 discs from src with the help of tar to buf
// Subproblem f(i-1): move the top i-1 disks from src to buf using tar
dfs(i - 1, src, tar, buf);
// Subproblem f(1): move the remaining one disc from src to tar
// Subproblem f(1): move the remaining disk from src to tar
move(src, tar);
// Subproblem f(i-1): move the top i-1 discs from buf with the help of src to tar
// Subproblem f(i-1): move the top i-1 disks from buf to tar using src
dfs(i - 1, buf, src, tar);
}
/* Solve the Tower of Hanoi problem */
void solveHanota(vector<int> &A, vector<int> &B, vector<int> &C) {
int n = A.size();
// Move the top n discs from A with the help of B to C
// Move the top n disks from A to C using B
dfs(n, A, B, C);
}
/* Driver Code */
int main() {
// The tail of the list is the top of the pillar
// The tail of the list is the top of the rod
vector<int> A = {5, 4, 3, 2, 1};
vector<int> B = {};
vector<int> C = {};
@@ -9,25 +9,25 @@
/* Backtracking */
void backtrack(vector<int> &choices, int state, int n, vector<int> &res) {
// When climbing to the nth step, add 1 to the number of solutions
// When climbing to the n-th stair, add 1 to the solution count
if (state == n)
res[0]++;
// Traverse all choices
for (auto &choice : choices) {
// Pruning: do not allow climbing beyond the nth step
// Pruning: not allowed to go beyond the n-th stair
if (state + choice > n)
continue;
// Attempt: make a choice, update the state
// Attempt: make choice, update state
backtrack(choices, state + choice, n, res);
// Retract
// Backtrack
}
}
/* Climbing stairs: Backtracking */
int climbingStairsBacktrack(int n) {
vector<int> choices = {1, 2}; // Can choose to climb up 1 step or 2 steps
int state = 0; // Start climbing from the 0th step
vector<int> res = {0}; // Use res[0] to record the number of solutions
vector<int> choices = {1, 2}; // Can choose to climb up 1 or 2 stairs
int state = 0; // Start climbing from the 0-th stair
vector<int> res = {0}; // Use res[0] to record the solution count
backtrack(choices, state, n, res);
return res[0];
}
@@ -37,7 +37,7 @@ int main() {
int n = 9;
int res = climbingStairsBacktrack(n);
cout << "There are " << res << " solutions to climb " << n << " stairs" << endl;
cout << "Climbing " << n << " stairs has " << res << " solutions" << endl;
return 0;
}
@@ -6,14 +6,14 @@
#include "../utils/common.hpp"
/* Constrained climbing stairs: Dynamic programming */
/* Climbing stairs with constraint: Dynamic programming */
int climbingStairsConstraintDP(int n) {
if (n == 1 || n == 2) {
return 1;
}
// Initialize dp table, used to store subproblem solutions
// Initialize dp table, used to store solutions to subproblems
vector<vector<int>> dp(n + 1, vector<int>(3, 0));
// Initial state: preset the smallest subproblem solution
// Initial state: preset the solution to the smallest subproblem
dp[1][1] = 1;
dp[1][2] = 0;
dp[2][1] = 0;
@@ -31,7 +31,7 @@ int main() {
int n = 9;
int res = climbingStairsConstraintDP(n);
cout << "There are " << res << " solutions to climb " << n << " stairs" << endl;
cout << "Climbing " << n << " stairs has " << res << " solutions" << endl;
return 0;
}
@@ -26,7 +26,7 @@ int main() {
int n = 9;
int res = climbingStairsDFS(n);
cout << "There are " << res << " solutions to climb " << n << " stairs" << endl;
cout << "Climbing " << n << " stairs has " << res << " solutions" << endl;
return 0;
}
@@ -6,12 +6,12 @@
#include "../utils/common.hpp"
/* Memoized search */
/* Memoization search */
int dfs(int i, vector<int> &mem) {
// Known dp[1] and dp[2], return them
if (i == 1 || i == 2)
return i;
// If there is a record for dp[i], return it
// If record dp[i] exists, return it directly
if (mem[i] != -1)
return mem[i];
// dp[i] = dp[i-1] + dp[i-2]
@@ -21,9 +21,9 @@ int dfs(int i, vector<int> &mem) {
return count;
}
/* Climbing stairs: Memoized search */
/* Climbing stairs: Memoization search */
int climbingStairsDFSMem(int n) {
// mem[i] records the total number of solutions for climbing to the ith step, -1 means no record
// mem[i] records the total number of solutions to climb to the i-th stair, -1 means no record
vector<int> mem(n + 1, -1);
return dfs(n, mem);
}
@@ -33,7 +33,7 @@ int main() {
int n = 9;
int res = climbingStairsDFSMem(n);
cout << "There are " << res << " solutions to climb " << n << " stairs" << endl;
cout << "Climbing " << n << " stairs has " << res << " solutions" << endl;
return 0;
}
@@ -10,9 +10,9 @@
int climbingStairsDP(int n) {
if (n == 1 || n == 2)
return n;
// Initialize dp table, used to store subproblem solutions
// Initialize dp table, used to store solutions to subproblems
vector<int> dp(n + 1);
// Initial state: preset the smallest subproblem solution
// Initial state: preset the solution to the smallest subproblem
dp[1] = 1;
dp[2] = 2;
// State transition: gradually solve larger subproblems from smaller ones
@@ -40,10 +40,10 @@ int main() {
int n = 9;
int res = climbingStairsDP(n);
cout << "There are " << res << " solutions to climb " << n << " stairs" << endl;
cout << "Climbing " << n << " stairs has " << res << " solutions" << endl;
res = climbingStairsDPComp(n);
cout << "There are " << res << " solutions to climb " << n << " stairs" << endl;
cout << "Climbing " << n << " stairs has " << res << " solutions" << endl;
return 0;
}
@@ -16,14 +16,14 @@ int coinChangeDP(vector<int> &coins, int amt) {
for (int a = 1; a <= amt; a++) {
dp[0][a] = MAX;
}
// State transition: the rest of the rows and columns
// State transition: rest of the rows and columns
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If exceeding the target amount, do not choose coin i
// If exceeds target amount, don't select coin i
dp[i][a] = dp[i - 1][a];
} else {
// The smaller value between not choosing and choosing coin i
// The smaller value between not selecting and selecting coin i
dp[i][a] = min(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1);
}
}
@@ -42,10 +42,10 @@ int coinChangeDPComp(vector<int> &coins, int amt) {
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If exceeding the target amount, do not choose coin i
// If exceeds target amount, don't select coin i
dp[a] = dp[a];
} else {
// The smaller value between not choosing and choosing coin i
// The smaller value between not selecting and selecting coin i
dp[a] = min(dp[a], dp[a - coins[i - 1]] + 1);
}
}
@@ -60,11 +60,11 @@ int main() {
// Dynamic programming
int res = coinChangeDP(coins, amt);
cout << "The minimum number of coins required to make up the target amount is " << res << endl;
cout << "Minimum number of coins needed to make target amount is " << res << endl;
// Space-optimized dynamic programming
res = coinChangeDPComp(coins, amt);
cout << "The minimum number of coins required to make up the target amount is " << res << endl;
cout << "Minimum number of coins needed to make target amount is " << res << endl;
return 0;
}
@@ -19,10 +19,10 @@ int coinChangeIIDP(vector<int> &coins, int amt) {
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If exceeding the target amount, do not choose coin i
// If exceeds target amount, don't select coin i
dp[i][a] = dp[i - 1][a];
} else {
// The sum of the two options of not choosing and choosing coin i
// Sum of the two options: not selecting and selecting coin i
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]];
}
}
@@ -40,10 +40,10 @@ int coinChangeIIDPComp(vector<int> &coins, int amt) {
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If exceeding the target amount, do not choose coin i
// If exceeds target amount, don't select coin i
dp[a] = dp[a];
} else {
// The sum of the two options of not choosing and choosing coin i
// Sum of the two options: not selecting and selecting coin i
dp[a] = dp[a] + dp[a - coins[i - 1]];
}
}
@@ -58,11 +58,11 @@ int main() {
// Dynamic programming
int res = coinChangeIIDP(coins, amt);
cout << "The number of coin combinations to make up the target amount is " << res << endl;
cout << "Number of coin combinations to make target amount is " << res << endl;
// Space-optimized dynamic programming
res = coinChangeIIDPComp(coins, amt);
cout << "The number of coin combinations to make up the target amount is " << res << endl;
cout << "Number of coin combinations to make target amount is " << res << endl;
return 0;
}
@@ -6,50 +6,50 @@
#include "../utils/common.hpp"
/* Edit distance: Brute force search */
/* Edit distance: Brute-force search */
int editDistanceDFS(string s, string t, int i, int j) {
// If both s and t are empty, return 0
if (i == 0 && j == 0)
return 0;
// If s is empty, return the length of t
// If s is empty, return length of t
if (i == 0)
return j;
// If t is empty, return the length of s
// If t is empty, return length of s
if (j == 0)
return i;
// If the two characters are equal, skip these two characters
// If two characters are equal, skip both characters
if (s[i - 1] == t[j - 1])
return editDistanceDFS(s, t, i - 1, j - 1);
// The minimum number of edits = the minimum number of edits from three operations (insert, remove, replace) + 1
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
int insert = editDistanceDFS(s, t, i, j - 1);
int del = editDistanceDFS(s, t, i - 1, j);
int replace = editDistanceDFS(s, t, i - 1, j - 1);
// Return the minimum number of edits
// Return minimum edit steps
return min(min(insert, del), replace) + 1;
}
/* Edit distance: Memoized search */
/* Edit distance: Memoization search */
int editDistanceDFSMem(string s, string t, vector<vector<int>> &mem, int i, int j) {
// If both s and t are empty, return 0
if (i == 0 && j == 0)
return 0;
// If s is empty, return the length of t
// If s is empty, return length of t
if (i == 0)
return j;
// If t is empty, return the length of s
// If t is empty, return length of s
if (j == 0)
return i;
// If there is a record, return it
// If there's a record, return it directly
if (mem[i][j] != -1)
return mem[i][j];
// If the two characters are equal, skip these two characters
// If two characters are equal, skip both characters
if (s[i - 1] == t[j - 1])
return editDistanceDFSMem(s, t, mem, i - 1, j - 1);
// The minimum number of edits = the minimum number of edits from three operations (insert, remove, replace) + 1
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
int insert = editDistanceDFSMem(s, t, mem, i, j - 1);
int del = editDistanceDFSMem(s, t, mem, i - 1, j);
int replace = editDistanceDFSMem(s, t, mem, i - 1, j - 1);
// Record and return the minimum number of edits
// Record and return minimum edit steps
mem[i][j] = min(min(insert, del), replace) + 1;
return mem[i][j];
}
@@ -65,14 +65,14 @@ int editDistanceDP(string s, string t) {
for (int j = 1; j <= m; j++) {
dp[0][j] = j;
}
// State transition: the rest of the rows and columns
// State transition: rest of the rows and columns
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (s[i - 1] == t[j - 1]) {
// If the two characters are equal, skip these two characters
// If two characters are equal, skip both characters
dp[i][j] = dp[i - 1][j - 1];
} else {
// The minimum number of edits = the minimum number of edits from three operations (insert, remove, replace) + 1
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
dp[i][j] = min(min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
}
}
@@ -88,22 +88,22 @@ int editDistanceDPComp(string s, string t) {
for (int j = 1; j <= m; j++) {
dp[j] = j;
}
// State transition: the rest of the rows
// State transition: rest of the rows
for (int i = 1; i <= n; i++) {
// State transition: first column
int leftup = dp[0]; // Temporarily store dp[i-1, j-1]
dp[0] = i;
// State transition: the rest of the columns
// State transition: rest of the columns
for (int j = 1; j <= m; j++) {
int temp = dp[j];
if (s[i - 1] == t[j - 1]) {
// If the two characters are equal, skip these two characters
// If two characters are equal, skip both characters
dp[j] = leftup;
} else {
// The minimum number of edits = the minimum number of edits from three operations (insert, remove, replace) + 1
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
dp[j] = min(min(dp[j - 1], dp[j]), leftup) + 1;
}
leftup = temp; // Update for the next round of dp[i-1, j-1]
leftup = temp; // Update for next round's dp[i-1, j-1]
}
}
return dp[m];
@@ -115,22 +115,22 @@ int main() {
string t = "pack";
int n = s.length(), m = t.length();
// Brute force search
// Brute-force search
int res = editDistanceDFS(s, t, n, m);
cout << "Changing " << s << " to " << t << " requires a minimum of " << res << " edits.\n";
cout << "Changing " << s << " to " << t << " requires a minimum of " << res << " edits";
// Memoized search
// Memoization search
vector<vector<int>> mem(n + 1, vector<int>(m + 1, -1));
res = editDistanceDFSMem(s, t, mem, n, m);
cout << "Changing " << s << " to " << t << " requires a minimum of " << res << " edits.\n";
cout << "Changing " << s << " to " << t << " requires a minimum of " << res << " edits";
// Dynamic programming
res = editDistanceDP(s, t);
cout << "Changing " << s << " to " << t << " requires a minimum of " << res << " edits.\n";
cout << "Changing " << s << " to " << t << " requires a minimum of " << res << " edits";
// Space-optimized dynamic programming
res = editDistanceDPComp(s, t);
cout << "Changing " << s << " to " << t << " requires a minimum of " << res << " edits.\n";
cout << "Changing " << s << " to " << t << " requires a minimum of " << res << " edits";
return 0;
}
@@ -4,46 +4,46 @@
using namespace std;
/* 0-1 Knapsack: Brute force search */
/* 0-1 knapsack: Brute-force search */
int knapsackDFS(vector<int> &wgt, vector<int> &val, int i, int c) {
// If all items have been chosen or the knapsack has no remaining capacity, return value 0
// If all items have been selected or knapsack has no remaining capacity, return value 0
if (i == 0 || c == 0) {
return 0;
}
// If exceeding the knapsack capacity, can only choose not to put it in the knapsack
// 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
int no = knapsackDFS(wgt, val, i - 1, c);
int yes = knapsackDFS(wgt, val, i - 1, c - wgt[i - 1]) + val[i - 1];
// Return the greater value of the two options
// Return the larger value of the two options
return max(no, yes);
}
/* 0-1 Knapsack: Memoized search */
/* 0-1 knapsack: Memoization search */
int knapsackDFSMem(vector<int> &wgt, vector<int> &val, vector<vector<int>> &mem, int i, int c) {
// If all items have been chosen or the knapsack has no remaining capacity, return value 0
// If all items have been selected or knapsack has no remaining capacity, return value 0
if (i == 0 || c == 0) {
return 0;
}
// If there is a record, return it
// If there's a record, return it directly
if (mem[i][c] != -1) {
return mem[i][c];
}
// If exceeding the knapsack capacity, can only choose not to put it in the knapsack
// 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
int no = knapsackDFSMem(wgt, val, mem, i - 1, c);
int yes = knapsackDFSMem(wgt, val, mem, i - 1, c - wgt[i - 1]) + val[i - 1];
// Record and return the greater value of the two options
// Record and return the larger value of the two options
mem[i][c] = max(no, yes);
return mem[i][c];
}
/* 0-1 Knapsack: Dynamic programming */
/* 0-1 knapsack: Dynamic programming */
int knapsackDP(vector<int> &wgt, vector<int> &val, int cap) {
int n = wgt.size();
// Initialize dp table
@@ -52,10 +52,10 @@ int knapsackDP(vector<int> &wgt, vector<int> &val, int cap) {
for (int i = 1; i <= n; i++) {
for (int c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// If exceeding the knapsack capacity, do not choose item i
// If exceeds knapsack capacity, don't select item i
dp[i][c] = dp[i - 1][c];
} else {
// The greater value between not choosing and choosing item i
// The larger value between not selecting and selecting item i
dp[i][c] = max(dp[i - 1][c], dp[i - 1][c - wgt[i - 1]] + val[i - 1]);
}
}
@@ -63,7 +63,7 @@ int knapsackDP(vector<int> &wgt, vector<int> &val, int cap) {
return dp[n][cap];
}
/* 0-1 Knapsack: Space-optimized dynamic programming */
/* 0-1 knapsack: Space-optimized dynamic programming */
int knapsackDPComp(vector<int> &wgt, vector<int> &val, int cap) {
int n = wgt.size();
// Initialize dp table
@@ -73,7 +73,7 @@ int knapsackDPComp(vector<int> &wgt, vector<int> &val, int cap) {
// Traverse in reverse order
for (int c = cap; c >= 1; c--) {
if (wgt[i - 1] <= c) {
// The greater value between not choosing and choosing item i
// The larger value between not selecting and selecting item i
dp[c] = max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
}
}
@@ -88,22 +88,22 @@ int main() {
int cap = 50;
int n = wgt.size();
// Brute force search
// Brute-force search
int res = knapsackDFS(wgt, val, n, cap);
cout << "The maximum value within the bag capacity is " << res << endl;
cout << "Maximum item value not exceeding knapsack capacity is " << res << endl;
// Memoized search
// Memoization search
vector<vector<int>> mem(n + 1, vector<int>(cap + 1, -1));
res = knapsackDFSMem(wgt, val, mem, n, cap);
cout << "The maximum value within the bag capacity is " << res << endl;
cout << "Maximum item value not exceeding knapsack capacity is " << res << endl;
// Dynamic programming
res = knapsackDP(wgt, val, cap);
cout << "The maximum value within the bag capacity is " << res << endl;
cout << "Maximum item value not exceeding knapsack capacity is " << res << endl;
// Space-optimized dynamic programming
res = knapsackDPComp(wgt, val, cap);
cout << "The maximum value within the bag capacity is " << res << endl;
cout << "Maximum item value not exceeding knapsack capacity is " << res << endl;
return 0;
}
@@ -6,14 +6,14 @@
#include "../utils/common.hpp"
/* Climbing stairs with minimum cost: Dynamic programming */
/* Minimum cost climbing stairs: Dynamic programming */
int minCostClimbingStairsDP(vector<int> &cost) {
int n = cost.size() - 1;
if (n == 1 || n == 2)
return cost[n];
// Initialize dp table, used to store subproblem solutions
// Initialize dp table, used to store solutions to subproblems
vector<int> dp(n + 1);
// Initial state: preset the smallest subproblem solution
// 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
@@ -23,7 +23,7 @@ int minCostClimbingStairsDP(vector<int> &cost) {
return dp[n];
}
/* Climbing stairs with minimum cost: Space-optimized dynamic programming */
/* Minimum cost climbing stairs: Space-optimized dynamic programming */
int minCostClimbingStairsDPComp(vector<int> &cost) {
int n = cost.size() - 1;
if (n == 1 || n == 2)
@@ -40,14 +40,14 @@ int minCostClimbingStairsDPComp(vector<int> &cost) {
/* Driver Code */
int main() {
vector<int> cost = {0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1};
cout << "Input the cost list for stairs";
cout << "Input stair cost list is ";
printVector(cost);
int res = minCostClimbingStairsDP(cost);
cout << "Minimum cost to climb the stairs " << res << endl;
cout << "Minimum cost to climb stairs is " << res << endl;
res = minCostClimbingStairsDPComp(cost);
cout << "Minimum cost to climb the stairs " << res << endl;
cout << "Minimum cost to climb stairs is " << res << endl;
return 0;
}
@@ -6,41 +6,41 @@
#include "../utils/common.hpp"
/* Minimum path sum: Brute force search */
/* Minimum path sum: Brute-force search */
int minPathSumDFS(vector<vector<int>> &grid, int i, int j) {
// If it's the top-left cell, terminate the search
if (i == 0 && j == 0) {
return grid[0][0];
}
// If the row or column index is out of bounds, return a +∞ cost
// If row or column index is out of bounds, return +∞ cost
if (i < 0 || j < 0) {
return INT_MAX;
}
// Calculate the minimum path cost from the top-left to (i-1, j) and (i, j-1)
// Calculate the minimum path cost from top-left to (i-1, j) and (i, j-1)
int up = minPathSumDFS(grid, i - 1, j);
int left = minPathSumDFS(grid, i, j - 1);
// Return the minimum path cost from the top-left to (i, j)
// Return the minimum path cost from top-left to (i, j)
return min(left, up) != INT_MAX ? min(left, up) + grid[i][j] : INT_MAX;
}
/* Minimum path sum: Memoized search */
/* Minimum path sum: Memoization search */
int minPathSumDFSMem(vector<vector<int>> &grid, vector<vector<int>> &mem, int i, int j) {
// If it's the top-left cell, terminate the search
if (i == 0 && j == 0) {
return grid[0][0];
}
// If the row or column index is out of bounds, return a +∞ cost
// If row or column index is out of bounds, return +∞ cost
if (i < 0 || j < 0) {
return INT_MAX;
}
// If there is a record, return it
// If there's a record, return it directly
if (mem[i][j] != -1) {
return mem[i][j];
}
// The minimum path cost from the left and top cells
// Minimum path cost for left and upper cells
int up = minPathSumDFSMem(grid, mem, i - 1, j);
int left = minPathSumDFSMem(grid, mem, i, j - 1);
// Record and return the minimum path cost from the top-left to (i, j)
// Record and return the minimum path cost from top-left to (i, j)
mem[i][j] = min(left, up) != INT_MAX ? min(left, up) + grid[i][j] : INT_MAX;
return mem[i][j];
}
@@ -59,7 +59,7 @@ int minPathSumDP(vector<vector<int>> &grid) {
for (int i = 1; i < n; i++) {
dp[i][0] = dp[i - 1][0] + grid[i][0];
}
// State transition: the rest of the rows and columns
// State transition: rest of the rows and columns
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
dp[i][j] = min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
@@ -78,11 +78,11 @@ int minPathSumDPComp(vector<vector<int>> &grid) {
for (int j = 1; j < m; j++) {
dp[j] = dp[j - 1] + grid[0][j];
}
// State transition: the rest of the rows
// State transition: rest of the rows
for (int i = 1; i < n; i++) {
// State transition: first column
dp[0] = dp[0] + grid[i][0];
// State transition: the rest of the columns
// State transition: rest of the columns
for (int j = 1; j < m; j++) {
dp[j] = min(dp[j - 1], dp[j]) + grid[i][j];
}
@@ -95,22 +95,22 @@ int main() {
vector<vector<int>> grid = {{1, 3, 1, 5}, {2, 2, 4, 2}, {5, 3, 2, 1}, {4, 3, 5, 2}};
int n = grid.size(), m = grid[0].size();
// Brute force search
// Brute-force search
int res = minPathSumDFS(grid, n - 1, m - 1);
cout << "The minimum path sum from the top left corner to the bottom right corner is " << res << endl;
cout << "Minimum path sum from top-left to bottom-right is " << res << endl;
// Memoized search
// Memoization search
vector<vector<int>> mem(n, vector<int>(m, -1));
res = minPathSumDFSMem(grid, mem, n - 1, m - 1);
cout << "The minimum path sum from the top left corner to the bottom right corner is " << res << endl;
cout << "Minimum path sum from top-left to bottom-right is " << res << endl;
// Dynamic programming
res = minPathSumDP(grid);
cout << "The minimum path sum from the top left corner to the bottom right corner is " << res << endl;
cout << "Minimum path sum from top-left to bottom-right is " << res << endl;
// Space-optimized dynamic programming
res = minPathSumDPComp(grid);
cout << "The minimum path sum from the top left corner to the bottom right corner is " << res << endl;
cout << "Minimum path sum from top-left to bottom-right is " << res << endl;
return 0;
}
@@ -6,7 +6,7 @@
#include "../utils/common.hpp"
/* Complete knapsack: Dynamic programming */
/* Unbounded knapsack: Dynamic programming */
int unboundedKnapsackDP(vector<int> &wgt, vector<int> &val, int cap) {
int n = wgt.size();
// Initialize dp table
@@ -15,10 +15,10 @@ int unboundedKnapsackDP(vector<int> &wgt, vector<int> &val, int cap) {
for (int i = 1; i <= n; i++) {
for (int c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// If exceeding the knapsack capacity, do not choose item i
// If exceeds knapsack capacity, don't select item i
dp[i][c] = dp[i - 1][c];
} else {
// The greater value between not choosing and choosing item i
// The larger value between not selecting and selecting item i
dp[i][c] = max(dp[i - 1][c], dp[i][c - wgt[i - 1]] + val[i - 1]);
}
}
@@ -26,7 +26,7 @@ int unboundedKnapsackDP(vector<int> &wgt, vector<int> &val, int cap) {
return dp[n][cap];
}
/* Complete knapsack: Space-optimized dynamic programming */
/* Unbounded knapsack: Space-optimized dynamic programming */
int unboundedKnapsackDPComp(vector<int> &wgt, vector<int> &val, int cap) {
int n = wgt.size();
// Initialize dp table
@@ -35,10 +35,10 @@ int unboundedKnapsackDPComp(vector<int> &wgt, vector<int> &val, int cap) {
for (int i = 1; i <= n; i++) {
for (int c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// If exceeding the knapsack capacity, do not choose item i
// If exceeds knapsack capacity, don't select item i
dp[c] = dp[c];
} else {
// The greater value between not choosing and choosing item i
// The larger value between not selecting and selecting item i
dp[c] = max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
}
}
@@ -54,11 +54,11 @@ int main() {
// Dynamic programming
int res = unboundedKnapsackDP(wgt, val, cap);
cout << "The maximum value within the bag capacity is " << res << endl;
cout << "Maximum item value not exceeding knapsack capacity is " << res << endl;
// Space-optimized dynamic programming
res = unboundedKnapsackDPComp(wgt, val, cap);
cout << "The maximum value within the bag capacity is " << res << endl;
cout << "Maximum item value not exceeding knapsack capacity is " << res << endl;
return 0;
}
@@ -12,7 +12,7 @@ class GraphAdjList {
// Adjacency list, key: vertex, value: all adjacent vertices of that vertex
unordered_map<Vertex *, vector<Vertex *>> adjList;
/* Remove a specified node from vector */
/* Remove specified node from vector */
void remove(vector<Vertex *> &vec, Vertex *vet) {
for (int i = 0; i < vec.size(); i++) {
if (vec[i] == vet) {
@@ -59,7 +59,7 @@ class GraphAdjList {
void addVertex(Vertex *vet) {
if (adjList.count(vet))
return;
// Add a new linked list to the adjacency list
// Add a new linked list in the adjacency list
adjList[vet] = vector<Vertex *>();
}
@@ -67,15 +67,15 @@ class GraphAdjList {
void removeVertex(Vertex *vet) {
if (!adjList.count(vet))
throw invalid_argument("Vertex does not exist");
// Remove the vertex vet's corresponding linked list from the adjacency list
// Remove the linked list corresponding to vertex vet in the adjacency list
adjList.erase(vet);
// Traverse other vertices' linked lists, removing all edges containing vet
// Traverse the linked lists of other vertices and remove all edges containing vet
for (auto &adj : adjList) {
remove(adj.second, vet);
}
}
/* Print the adjacency list */
/* Print adjacency list */
void print() {
cout << "Adjacency list =" << endl;
for (auto &adj : adjList) {
@@ -87,4 +87,4 @@ class GraphAdjList {
}
};
// See test case in graph_adjacency_list_test.cpp
// See graph_adjacency_list_test.cpp for test cases
@@ -8,36 +8,36 @@
/* Driver Code */
int main() {
/* Initialize undirected graph */
/* Add edge */
vector<Vertex *> v = valsToVets(vector<int>{1, 3, 2, 5, 4});
vector<vector<Vertex *>> edges = {{v[0], v[1]}, {v[0], v[3]}, {v[1], v[2]},
{v[2], v[3]}, {v[2], v[4]}, {v[3], v[4]}};
GraphAdjList graph(edges);
cout << "\nAfter initialization, the graph is" << endl;
cout << "\nAfter initialization, graph is" << endl;
graph.print();
/* Add edge */
// Vertices 1, 2 i.e., v[0], v[2]
// Vertices 1, 3 are v[0], v[1]
graph.addEdge(v[0], v[2]);
cout << "\nAfter adding edge 1-2, the graph is" << endl;
cout << "\nAfter adding edge 1-2, graph is" << endl;
graph.print();
/* Remove edge */
// Vertices 1, 3 i.e., v[0], v[1]
// Vertex 3 is v[1]
graph.removeEdge(v[0], v[1]);
cout << "\nAfter removing edge 1-3, the graph is" << endl;
cout << "\nAfter removing edge 1-3, graph is" << endl;
graph.print();
/* Add vertex */
Vertex *v5 = new Vertex(6);
graph.addVertex(v5);
cout << "\nAfter adding vertex 6, the graph is" << endl;
cout << "\nAfter adding vertex 6, graph is" << endl;
graph.print();
/* Remove vertex */
// Vertex 3 i.e., v[1]
// Vertex 3 is v[1]
graph.removeVertex(v[1]);
cout << "\nAfter removing vertex 3, the graph is" << endl;
cout << "\nAfter removing vertex 3, graph is" << endl;
graph.print();
// Free memory
@@ -8,8 +8,8 @@
/* Undirected graph class based on adjacency matrix */
class GraphAdjMat {
vector<int> vertices; // Vertex list, elements represent "vertex value", index represents "vertex index"
vector<vector<int>> adjMat; // Adjacency matrix, row and column indices correspond to "vertex index"
vector<int> vertices; // Vertex list, where the element represents the "vertex value" and the index represents the "vertex index"
vector<vector<int>> adjMat; // Adjacency matrix, where the row and column indices correspond to the "vertex index"
public:
/* Constructor */
@@ -19,7 +19,7 @@ class GraphAdjMat {
addVertex(val);
}
// Add edge
// Edges elements represent vertex indices
// Note that the edges elements represent vertex indices, i.e., corresponding to the vertices element indices
for (const vector<int> &edge : edges) {
addEdge(edge[0], edge[1]);
}
@@ -33,7 +33,7 @@ class GraphAdjMat {
/* Add vertex */
void addVertex(int val) {
int n = size();
// Add new vertex value to the vertex list
// Add the value of the new vertex to the vertex list
vertices.push_back(val);
// Add a row to the adjacency matrix
adjMat.emplace_back(vector<int>(n, 0));
@@ -48,30 +48,30 @@ class GraphAdjMat {
if (index >= size()) {
throw out_of_range("Vertex does not exist");
}
// Remove vertex at `index` from the vertex list
// Remove the vertex at index from the vertex list
vertices.erase(vertices.begin() + index);
// Remove the row at `index` from the adjacency matrix
// Remove the row at index from the adjacency matrix
adjMat.erase(adjMat.begin() + index);
// Remove the column at `index` from the adjacency matrix
// Remove the column at index from the adjacency matrix
for (vector<int> &row : adjMat) {
row.erase(row.begin() + index);
}
}
/* Add edge */
// Parameters i, j correspond to vertices element indices
// Parameters i, j correspond to the vertices element indices
void addEdge(int i, int j) {
// Handle index out of bounds and equality
if (i < 0 || j < 0 || i >= size() || j >= size() || i == j) {
throw out_of_range("Vertex does not exist");
}
// In an undirected graph, the adjacency matrix is symmetric about the main diagonal, i.e., satisfies (i, j) == (j, i)
// In an undirected graph, the adjacency matrix is symmetric about the main diagonal, i.e., (i, j) == (j, i)
adjMat[i][j] = 1;
adjMat[j][i] = 1;
}
/* Remove edge */
// Parameters i, j correspond to vertices element indices
// Parameters i, j correspond to the vertices element indices
void removeEdge(int i, int j) {
// Handle index out of bounds and equality
if (i < 0 || j < 0 || i >= size() || j >= size() || i == j) {
@@ -92,35 +92,35 @@ class GraphAdjMat {
/* Driver Code */
int main() {
/* Initialize undirected graph */
// Edges elements represent vertex indices
/* Add edge */
// Note that the edges elements represent vertex indices, i.e., corresponding to the vertices element indices
vector<int> vertices = {1, 3, 2, 5, 4};
vector<vector<int>> edges = {{0, 1}, {0, 3}, {1, 2}, {2, 3}, {2, 4}, {3, 4}};
GraphAdjMat graph(vertices, edges);
cout << "\nAfter initialization, the graph is" << endl;
cout << "\nAfter initialization, graph is" << endl;
graph.print();
/* Add edge */
// Indices of vertices 1, 2 are 0, 2 respectively
// Add vertex
graph.addEdge(0, 2);
cout << "\nAfter adding edge 1-2, the graph is" << endl;
cout << "\nAfter adding edge 1-2, graph is" << endl;
graph.print();
/* Remove edge */
// Indices of vertices 1, 3 are 0, 1 respectively
// Vertices 1, 3 have indices 0, 1 respectively
graph.removeEdge(0, 1);
cout << "\nAfter removing edge 1-3, the graph is" << endl;
cout << "\nAfter removing edge 1-3, graph is" << endl;
graph.print();
/* Add vertex */
graph.addVertex(6);
cout << "\nAfter adding vertex 6, the graph is" << endl;
cout << "\nAfter adding vertex 6, graph is" << endl;
graph.print();
/* Remove vertex */
// Index of vertex 3 is 1
// Vertex 3 has index 1
graph.removeVertex(1);
cout << "\nAfter removing vertex 3, the graph is" << endl;
cout << "\nAfter removing vertex 3, graph is" << endl;
graph.print();
return 0;
+9 -9
View File
@@ -8,11 +8,11 @@
#include "./graph_adjacency_list.cpp"
/* Breadth-first traversal */
// Use adjacency list to represent the graph, to obtain all adjacent vertices of a specified vertex
// Use adjacency list to represent the graph, in order to obtain all adjacent vertices of a specified vertex
vector<Vertex *> graphBFS(GraphAdjList &graph, Vertex *startVet) {
// Vertex traversal sequence
vector<Vertex *> res;
// Hash set, used to record visited vertices
// Hash set for recording vertices that have been visited
unordered_set<Vertex *> visited = {startVet};
// Queue used to implement BFS
queue<Vertex *> que;
@@ -20,29 +20,29 @@ vector<Vertex *> graphBFS(GraphAdjList &graph, Vertex *startVet) {
// Starting from vertex vet, loop until all vertices are visited
while (!que.empty()) {
Vertex *vet = que.front();
que.pop(); // Dequeue the vertex at the head of the queue
que.pop(); // Dequeue the front vertex
res.push_back(vet); // Record visited vertex
// Traverse all adjacent vertices of that vertex
// Traverse all adjacent vertices of this vertex
for (auto adjVet : graph.adjList[vet]) {
if (visited.count(adjVet))
continue; // Skip already visited vertices
continue; // Skip vertices that have been visited
que.push(adjVet); // Only enqueue unvisited vertices
visited.emplace(adjVet); // Mark the vertex as visited
visited.emplace(adjVet); // Mark this vertex as visited
}
}
// Return the vertex traversal sequence
// Return vertex traversal sequence
return res;
}
/* Driver Code */
int main() {
/* Initialize undirected graph */
/* Add edge */
vector<Vertex *> v = valsToVets({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
vector<vector<Vertex *>> edges = {{v[0], v[1]}, {v[0], v[3]}, {v[1], v[2]}, {v[1], v[4]},
{v[2], v[5]}, {v[3], v[4]}, {v[3], v[6]}, {v[4], v[5]},
{v[4], v[7]}, {v[5], v[8]}, {v[6], v[7]}, {v[7], v[8]}};
GraphAdjList graph(edges);
cout << "\nAfter initialization, the graph is\n";
cout << "\nAfter initialization, graph is\\n";
graph.print();
/* Breadth-first traversal */
+7 -7
View File
@@ -10,22 +10,22 @@
/* Depth-first traversal helper function */
void dfs(GraphAdjList &graph, unordered_set<Vertex *> &visited, vector<Vertex *> &res, Vertex *vet) {
res.push_back(vet); // Record visited vertex
visited.emplace(vet); // Mark the vertex as visited
// Traverse all adjacent vertices of that vertex
visited.emplace(vet); // Mark this vertex as visited
// Traverse all adjacent vertices of this vertex
for (Vertex *adjVet : graph.adjList[vet]) {
if (visited.count(adjVet))
continue; // Skip already visited vertices
continue; // Skip vertices that have been visited
// Recursively visit adjacent vertices
dfs(graph, visited, res, adjVet);
}
}
/* Depth-first traversal */
// Use adjacency list to represent the graph, to obtain all adjacent vertices of a specified vertex
// Use adjacency list to represent the graph, in order to obtain all adjacent vertices of a specified vertex
vector<Vertex *> graphDFS(GraphAdjList &graph, Vertex *startVet) {
// Vertex traversal sequence
vector<Vertex *> res;
// Hash set, used to record visited vertices
// Hash set for recording vertices that have been visited
unordered_set<Vertex *> visited;
dfs(graph, visited, res, startVet);
return res;
@@ -33,12 +33,12 @@ vector<Vertex *> graphDFS(GraphAdjList &graph, Vertex *startVet) {
/* Driver Code */
int main() {
/* Initialize undirected graph */
/* Add edge */
vector<Vertex *> v = valsToVets(vector<int>{0, 1, 2, 3, 4, 5, 6});
vector<vector<Vertex *>> edges = {{v[0], v[1]}, {v[0], v[3]}, {v[1], v[2]},
{v[2], v[5]}, {v[4], v[5]}, {v[5], v[6]}};
GraphAdjList graph(edges);
cout << "\nAfter initialization, the graph is" << endl;
cout << "\nAfter initialization, graph is" << endl;
graph.print();
/* Depth-first traversal */
@@ -6,14 +6,14 @@
#include "../utils/common.hpp"
/* Coin change: Greedy */
/* Coin change: Greedy algorithm */
int coinChangeGreedy(vector<int> &coins, int amt) {
// Assume coins list is ordered
// Assume coins list is sorted
int i = coins.size() - 1;
int count = 0;
// Loop for greedy selection until no remaining amount
// Loop to make greedy choices until no remaining amount
while (amt > 0) {
// Find the smallest coin close to and less than the remaining amount
// Find the coin that is less than and closest to the remaining amount
while (i > 0 && coins[i] > amt) {
i--;
}
@@ -27,34 +27,34 @@ int coinChangeGreedy(vector<int> &coins, int amt) {
/* Driver Code */
int main() {
// Greedy: can ensure finding a global optimal solution
// Greedy algorithm: Can guarantee finding the global optimal solution
vector<int> coins = {1, 5, 10, 20, 50, 100};
int amt = 186;
int res = coinChangeGreedy(coins, amt);
cout << "\ncoins = ";
printVector(coins);
cout << "amt = " << amt << endl;
cout << "The minimum number of coins required to make up " << amt << " is " << res << endl;
cout << "Minimum number of coins needed to make " << amt << " is " << res << endl;
// Greedy: cannot ensure finding a global optimal solution
// Greedy algorithm: Cannot guarantee finding the global optimal solution
coins = {1, 20, 50};
amt = 60;
res = coinChangeGreedy(coins, amt);
cout << "\ncoins = ";
printVector(coins);
cout << "amt = " << amt << endl;
cout << "The minimum number of coins required to make up " << amt << " is " << res << endl;
cout << "In reality, the minimum number needed is 3, i.e., 20 + 20 + 20" << endl;
cout << "Minimum number of coins needed to make " << amt << " is " << res << endl;
cout << "Actually the minimum number needed is 3, i.e., 20 + 20 + 20" << endl;
// Greedy: cannot ensure finding a global optimal solution
// Greedy algorithm: Cannot guarantee finding the global optimal solution
coins = {1, 49, 50};
amt = 98;
res = coinChangeGreedy(coins, amt);
cout << "\ncoins = ";
printVector(coins);
cout << "amt = " << amt << endl;
cout << "The minimum number of coins required to make up " << amt << " is " << res << endl;
cout << "In reality, the minimum number needed is 2, i.e., 49 + 49" << endl;
cout << "Minimum number of coins needed to make " << amt << " is " << res << endl;
cout << "Actually the minimum number needed is 2, i.e., 49 + 49" << endl;
return 0;
}
@@ -16,9 +16,9 @@ class Item {
}
};
/* Fractional knapsack: Greedy */
/* Fractional knapsack: Greedy algorithm */
double fractionalKnapsack(vector<int> &wgt, vector<int> &val, int cap) {
// Create an item list, containing two properties: weight, value
// Create item list with two attributes: weight, value
vector<Item> items;
for (int i = 0; i < wgt.size(); i++) {
items.push_back(Item(wgt[i], val[i]));
@@ -29,13 +29,13 @@ double fractionalKnapsack(vector<int> &wgt, vector<int> &val, int cap) {
double res = 0;
for (auto &item : items) {
if (item.w <= cap) {
// If the remaining capacity is sufficient, put the entire item into the knapsack
// If remaining capacity is sufficient, put the entire current item into the knapsack
res += item.v;
cap -= item.w;
} else {
// If the remaining capacity is insufficient, put part of the item into the knapsack
// If remaining capacity is insufficient, put part of the current item into the knapsack
res += (double)item.v / item.w * cap;
// No remaining capacity left, thus break the loop
// No remaining capacity, so break out of the loop
break;
}
}
@@ -50,7 +50,7 @@ int main() {
// Greedy algorithm
double res = fractionalKnapsack(wgt, val, cap);
cout << "The maximum value within the bag capacity is " << res << endl;
cout << "Maximum item value not exceeding knapsack capacity is " << res << endl;
return 0;
}
+5 -5
View File
@@ -6,15 +6,15 @@
#include "../utils/common.hpp"
/* Maximum capacity: Greedy */
/* Max capacity: Greedy algorithm */
int maxCapacity(vector<int> &ht) {
// Initialize i, j, making them split the array at both ends
// Initialize i, j to be at both ends of the array
int i = 0, j = ht.size() - 1;
// Initial maximum capacity is 0
// Initial max capacity is 0
int res = 0;
// Loop for greedy selection until the two boards meet
while (i < j) {
// Update maximum capacity
// Update max capacity
int cap = min(ht[i], ht[j]) * (j - i);
res = max(res, cap);
// Move the shorter board inward
@@ -33,7 +33,7 @@ int main() {
// Greedy algorithm
int res = maxCapacity(ht);
cout << "The maximum capacity is " << res << endl;
cout << "Maximum capacity is " << res << endl;
return 0;
}
@@ -6,17 +6,17 @@
#include "../utils/common.hpp"
/* Maximum product of cutting: Greedy */
/* Max product cutting: Greedy algorithm */
int maxProductCutting(int n) {
// When n <= 3, must cut out a 1
if (n <= 3) {
return 1 * (n - 1);
}
// Greedy cut out 3s, a is the number of 3s, b is the remainder
// Greedily cut out 3, a is the number of 3s, b is the remainder
int a = n / 3;
int b = n % 3;
if (b == 1) {
// When the remainder is 1, convert a pair of 1 * 3 into 2 * 2
// When the remainder is 1, convert a pair of 1 * 3 to 2 * 2
return (int)pow(3, a - 1) * 2 * 2;
}
if (b == 2) {
@@ -24,7 +24,7 @@ class ArrayHashMap {
public:
ArrayHashMap() {
// Initialize an array, containing 100 buckets
// Initialize array with 100 buckets
buckets = vector<Pair *>(100);
}
@@ -107,4 +107,4 @@ class ArrayHashMap {
}
};
// See test case in array_hash_map_test.cpp
// See array_hash_map_test.cpp for test cases
@@ -13,23 +13,23 @@ int main() {
/* Add operation */
// Add key-value pair (key, value) to the hash table
map.put(12836, "Ha");
map.put(15937, "Luo");
map.put(16750, "Suan");
map.put(13276, "Fa");
map.put(10583, "Ya");
cout << "\nAfter adding, the hash table is\nKey -> Value" << endl;
map.put(12836, "Xiao Ha");
map.put(15937, "Xiao Luo");
map.put(16750, "Xiao Suan");
map.put(13276, "Xiao Fa");
map.put(10583, "Xiao Ya");
cout << "\nAfter adding is complete, hash table is\nKey -> Value" << endl;
map.print();
/* Query operation */
// Enter key to the hash table, get value
// Input key into hash table to get value
string name = map.get(15937);
cout << "\nEnter student ID 15937, found name " << name << endl;
cout << "\nInput student ID 15937, query name " << name << endl;
/* Remove operation */
// Remove key-value pair (key, value) from the hash table
// Remove key-value pair (key, value) from hash table
map.remove(10583);
cout << "\nAfter removing 10583, the hash table is\nKey -> Value" << endl;
cout << "\nAfter removing 10583, hash table is\nKey -> Value" << endl;
map.print();
/* Traverse hash table */
@@ -38,12 +38,12 @@ int main() {
cout << kv->key << " -> " << kv->val << endl;
}
cout << "\nIndividually traverse keys Key" << endl;
cout << "\nTraverse keys only Key" << endl;
for (auto key : map.keySet()) {
cout << key << endl;
}
cout << "\nIndividually traverse values Value" << endl;
cout << "\nTraverse values only Value" << endl;
for (auto val : map.valueSet()) {
cout << val << endl;
}
@@ -10,20 +10,20 @@
int main() {
int num = 3;
size_t hashNum = hash<int>()(num);
cout << "The hash value of integer " << num << " is " << hashNum << "\n";
cout << "Hash value of integer " << num << " is " << hashNum << "\n";
bool bol = true;
size_t hashBol = hash<bool>()(bol);
cout << "The hash value of boolean " << bol << " is " << hashBol << "\n";
cout << "Hash value of boolean " << bol << " is " << hashBol << "\n";
double dec = 3.14159;
size_t hashDec = hash<double>()(dec);
cout << "The hash value of decimal " << dec << " is " << hashDec << "\n";
cout << "Hash value of decimal " << dec << " is " << hashDec << "\n";
string str = "Hello algorithm";
string str = "Hello Algo";
size_t hashStr = hash<string>()(str);
cout << "The hash value of string " << str << " is " << hashStr << "\n";
cout << "Hash value of string " << str << " is " << hashStr << "\n";
// In C++, the built-in std:hash() only provides hash values for basic data types
// Hash value calculation for arrays and objects must be implemented manually
// In C++, built-in std::hash() only provides hash calculation for basic data types
// Hash calculation for arrays and objects needs to be implemented manually
}
+11 -11
View File
@@ -13,23 +13,23 @@ int main() {
/* Add operation */
// Add key-value pair (key, value) to the hash table
map[12836] = "Ha";
map[15937] = "Luo";
map[16750] = "Suan";
map[13276] = "Fa";
map[10583] = "Ya";
cout << "\nAfter adding, the hash table is\nKey -> Value" << endl;
map[12836] = "Xiao Ha";
map[15937] = "Xiao Luo";
map[16750] = "Xiao Suan";
map[13276] = "Xiao Fa";
map[10583] = "Xiao Ya";
cout << "\nAfter adding is complete, hash table is\nKey -> Value" << endl;
printHashMap(map);
/* Query operation */
// Enter key to the hash table, get value
// Input key into hash table to get value
string name = map[15937];
cout << "\nEnter student ID 15937, found name " << name << endl;
cout << "\nInput student ID 15937, query name " << name << endl;
/* Remove operation */
// Remove key-value pair (key, value) from the hash table
// Remove key-value pair (key, value) from hash table
map.erase(10583);
cout << "\nAfter removing 10583, the hash table is\nKey -> Value" << endl;
cout << "\nAfter removing 10583, hash table is\nKey -> Value" << endl;
printHashMap(map);
/* Traverse hash table */
@@ -37,7 +37,7 @@ int main() {
for (auto kv : map) {
cout << kv.first << " -> " << kv.second << endl;
}
cout << "\nIterate through Key->Value using an iterator" << endl;
cout << "\nTraverse Key->Value using iterator" << endl;
for (auto iter = map.begin(); iter != map.end(); iter++) {
cout << iter->first << "->" << iter->second << endl;
}
@@ -6,7 +6,7 @@
#include "./array_hash_map.cpp"
/* Chained address hash table */
/* Hash table with separate chaining */
class HashMapChaining {
private:
int size; // Number of key-value pairs
@@ -44,31 +44,31 @@ class HashMapChaining {
/* Query operation */
string get(int key) {
int index = hashFunc(key);
// Traverse the bucket, if the key is found, return the corresponding val
// Traverse bucket, if key is found, return corresponding val
for (Pair *pair : buckets[index]) {
if (pair->key == key) {
return pair->val;
}
}
// If key not found, return an empty string
// Return empty string if key not found
return "";
}
/* Add operation */
void put(int key, string val) {
// When the load factor exceeds the threshold, perform expansion
// When load factor exceeds threshold, perform expansion
if (loadFactor() > loadThres) {
extend();
}
int index = hashFunc(key);
// Traverse the bucket, if the specified key is encountered, update the corresponding val and return
// Traverse bucket, if specified key is encountered, update corresponding val and return
for (Pair *pair : buckets[index]) {
if (pair->key == key) {
pair->val = val;
return;
}
}
// If the key is not found, add the key-value pair to the end
// If key does not exist, append key-value pair to the end
buckets[index].push_back(new Pair(key, val));
size++;
}
@@ -77,11 +77,11 @@ class HashMapChaining {
void remove(int key) {
int index = hashFunc(key);
auto &bucket = buckets[index];
// Traverse the bucket, remove the key-value pair from it
// Traverse bucket and remove key-value pair from it
for (int i = 0; i < bucket.size(); i++) {
if (bucket[i]->key == key) {
Pair *tmp = bucket[i];
bucket.erase(bucket.begin() + i); // Remove key-value pair
bucket.erase(bucket.begin() + i); // Remove key-value pair from it
delete tmp; // Free memory
size--;
return;
@@ -89,16 +89,16 @@ class HashMapChaining {
}
}
/* Extend hash table */
/* Expand hash table */
void extend() {
// Temporarily store the original hash table
vector<vector<Pair *>> bucketsTmp = buckets;
// Initialize the extended new hash table
// Initialize expanded new hash table
capacity *= extendRatio;
buckets.clear();
buckets.resize(capacity);
size = 0;
// Move key-value pairs from the original hash table to the new hash table
// Move key-value pairs from original hash table to new hash table
for (auto &bucket : bucketsTmp) {
for (Pair *pair : bucket) {
put(pair->key, pair->val);
@@ -127,23 +127,23 @@ int main() {
/* Add operation */
// Add key-value pair (key, value) to the hash table
map.put(12836, "Ha");
map.put(15937, "Luo");
map.put(16750, "Suan");
map.put(13276, "Fa");
map.put(10583, "Ya");
cout << "\nAfter adding, the hash table is\nKey -> Value" << endl;
map.put(12836, "Xiao Ha");
map.put(15937, "Xiao Luo");
map.put(16750, "Xiao Suan");
map.put(13276, "Xiao Fa");
map.put(10583, "Xiao Ya");
cout << "\nAfter adding is complete, hash table is\nKey -> Value" << endl;
map.print();
/* Query operation */
// Enter key to the hash table, get value
// Input key into hash table to get value
string name = map.get(13276);
cout << "\nEnter student ID 13276, found name " << name << endl;
cout << "\nInput student ID 13276, query name " << name << endl;
/* Remove operation */
// Remove key-value pair (key, value) from the hash table
// Remove key-value pair (key, value) from hash table
map.remove(12836);
cout << "\nAfter removing 12836, the hash table is\nKey -> Value" << endl;
cout << "\nAfter removing 12836, hash table is\nKey -> Value" << endl;
map.print();
return 0;
@@ -6,7 +6,7 @@
#include "./array_hash_map.cpp"
/* Open addressing hash table */
/* Hash table with open addressing */
class HashMapOpenAddressing {
private:
int size; // Number of key-value pairs
@@ -14,7 +14,7 @@ class HashMapOpenAddressing {
const double loadThres = 2.0 / 3.0; // Load factor threshold for triggering expansion
const int extendRatio = 2; // Expansion multiplier
vector<Pair *> buckets; // Bucket array
Pair *TOMBSTONE = new Pair(-1, "-1"); // Removal mark
Pair *TOMBSTONE = new Pair(-1, "-1"); // Removal marker
public:
/* Constructor */
@@ -41,15 +41,15 @@ class HashMapOpenAddressing {
return (double)size / capacity;
}
/* Search for the bucket index corresponding to key */
/* Search for bucket index corresponding to key */
int findBucket(int key) {
int index = hashFunc(key);
int firstTombstone = -1;
// Linear probing, break when encountering an empty bucket
while (buckets[index] != nullptr) {
// If the key is encountered, return the corresponding bucket index
// If key is encountered, return the corresponding bucket index
if (buckets[index]->key == key) {
// If a removal mark was encountered earlier, move the key-value pair to that index
// If a removal marker was encountered before, move the key-value pair to that index
if (firstTombstone != -1) {
buckets[firstTombstone] = buckets[index];
buckets[index] = TOMBSTONE;
@@ -57,52 +57,52 @@ class HashMapOpenAddressing {
}
return index; // Return bucket index
}
// Record the first encountered removal mark
// Record the first removal marker encountered
if (firstTombstone == -1 && buckets[index] == TOMBSTONE) {
firstTombstone = index;
}
// Calculate the bucket index, return to the head if exceeding the tail
// Calculate bucket index, wrap around to the head if past the tail
index = (index + 1) % capacity;
}
// If the key does not exist, return the index of the insertion point
// If key does not exist, return the index for insertion
return firstTombstone == -1 ? index : firstTombstone;
}
/* Query operation */
string get(int key) {
// Search for the bucket index corresponding to key
// Search for bucket index corresponding to key
int index = findBucket(key);
// If the key-value pair is found, return the corresponding val
// If key-value pair is found, return corresponding val
if (buckets[index] != nullptr && buckets[index] != TOMBSTONE) {
return buckets[index]->val;
}
// If key-value pair does not exist, return an empty string
// Return empty string if key-value pair does not exist
return "";
}
/* Add operation */
void put(int key, string val) {
// When the load factor exceeds the threshold, perform expansion
// When load factor exceeds threshold, perform expansion
if (loadFactor() > loadThres) {
extend();
}
// Search for the bucket index corresponding to key
// Search for bucket index corresponding to key
int index = findBucket(key);
// If the key-value pair is found, overwrite val and return
// If key-value pair is found, overwrite val and return
if (buckets[index] != nullptr && buckets[index] != TOMBSTONE) {
buckets[index]->val = val;
return;
}
// If the key-value pair does not exist, add the key-value pair
// If key-value pair does not exist, add the key-value pair
buckets[index] = new Pair(key, val);
size++;
}
/* Remove operation */
void remove(int key) {
// Search for the bucket index corresponding to key
// Search for bucket index corresponding to key
int index = findBucket(key);
// If the key-value pair is found, cover it with a removal mark
// If key-value pair is found, overwrite it with removal marker
if (buckets[index] != nullptr && buckets[index] != TOMBSTONE) {
delete buckets[index];
buckets[index] = TOMBSTONE;
@@ -110,15 +110,15 @@ class HashMapOpenAddressing {
}
}
/* Extend hash table */
/* Expand hash table */
void extend() {
// Temporarily store the original hash table
vector<Pair *> bucketsTmp = buckets;
// Initialize the extended new hash table
// Initialize expanded new hash table
capacity *= extendRatio;
buckets = vector<Pair *>(capacity, nullptr);
size = 0;
// Move key-value pairs from the original hash table to the new hash table
// Move key-value pairs from original hash table to new hash table
for (Pair *pair : bucketsTmp) {
if (pair != nullptr && pair != TOMBSTONE) {
put(pair->key, pair->val);
@@ -148,23 +148,23 @@ int main() {
// Add operation
// Add key-value pair (key, val) to the hash table
hashmap.put(12836, "Ha");
hashmap.put(15937, "Luo");
hashmap.put(16750, "Suan");
hashmap.put(13276, "Fa");
hashmap.put(10583, "Ya");
cout << "\nAfter adding, the hash table is\nKey -> Value" << endl;
hashmap.put(12836, "Xiao Ha");
hashmap.put(15937, "Xiao Luo");
hashmap.put(16750, "Xiao Suan");
hashmap.put(13276, "Xiao Fa");
hashmap.put(10583, "Xiao Ya");
cout << "\nAfter adding is complete, hash table is\nKey -> Value" << endl;
hashmap.print();
// Query operation
// Enter key to the hash table, get value val
// Input key into hash table to get value val
string name = hashmap.get(13276);
cout << "\nEnter student ID 13276, found name " << name << endl;
cout << "\nInput student ID 13276, query name " << name << endl;
// Remove operation
// Remove key-value pair (key, val) from the hash table
// Remove key-value pair (key, val) from hash table
hashmap.remove(16750);
cout << "\nAfter removing 16750, the hash table is\nKey -> Value" << endl;
cout << "\nAfter removing 16750, hash table is\nKey -> Value" << endl;
hashmap.print();
return 0;
+1 -1
View File
@@ -48,7 +48,7 @@ int rotHash(string key) {
/* Driver Code */
int main() {
string key = "Hello algorithm";
string key = "Hello Algo";
int hash = addHash(key);
cout << "Additive hash value is " << hash << endl;
+16 -16
View File
@@ -7,40 +7,40 @@
#include "../utils/common.hpp"
void testPush(priority_queue<int> &heap, int val) {
heap.push(val); // Push the element into heap
cout << "\nAfter element " << val << " is added to the heap" << endl;
heap.push(val); // Element enters heap
cout << "\nAfter element " << val << " pushes to heap" << endl;
printHeap(heap);
}
void testPop(priority_queue<int> &heap) {
int val = heap.top();
heap.pop();
cout << "\nAfter the top element " << val << " is removed from the heap" << endl;
cout << "\nAfter heap top element " << val << " pops from heap" << endl;
printHeap(heap);
}
/* Driver Code */
int main() {
/* Initialize the heap */
// Initialize min-heap
/* Initialize heap */
// Python's heapq module implements min heap by default
// priority_queue<int, vector<int>, greater<int>> minHeap;
// Initialize max-heap
// Consider negating the elements before entering the heap, which can reverse the size relationship, thus implementing max heap
priority_queue<int, vector<int>, less<int>> maxHeap;
cout << "\nThe following test case is for max-heap" << endl;
cout << "\nThe following test cases are for max heap" << endl;
/* Push the element into heap */
/* Element enters heap */
testPush(maxHeap, 1);
testPush(maxHeap, 3);
testPush(maxHeap, 2);
testPush(maxHeap, 5);
testPush(maxHeap, 4);
/* Access heap top element */
/* Check if heap is empty */
int peek = maxHeap.top();
cout << "\nTop element of the heap is " << peek << endl;
cout << "\nHeap top element is " << peek << endl;
/* Pop the element at the heap top */
/* Time complexity is O(n), not O(nlogn) */
testPop(maxHeap);
testPop(maxHeap);
testPop(maxHeap);
@@ -49,17 +49,17 @@ int main() {
/* Get heap size */
int size = maxHeap.size();
cout << "\nNumber of elements in the heap is " << size << endl;
cout << "\nHeap size is " << size << endl;
/* Determine if heap is empty */
/* Check if heap is empty */
bool isEmpty = maxHeap.empty();
cout << "\nIs the heap empty " << isEmpty << endl;
cout << "\nIs heap empty " << isEmpty << endl;
/* Enter list and build heap */
/* Input list and build heap */
// Time complexity is O(n), not O(nlogn)
vector<int> input{1, 3, 2, 5, 4};
priority_queue<int, vector<int>, greater<int>> minHeap(input.begin(), input.end());
cout << "After inputting the list and building a min-heap" << endl;
cout << "After input list and building min heap" << endl;
printHeap(minHeap);
return 0;
+31 -31
View File
@@ -6,10 +6,10 @@
#include "../utils/common.hpp"
/* Max-heap */
/* Max heap */
class MaxHeap {
private:
// Using a dynamic array to avoid the need for resizing
// Use dynamic array to avoid expansion issues
vector<int> maxHeap;
/* Get index of left child node */
@@ -24,34 +24,34 @@ class MaxHeap {
/* Get index of parent node */
int parent(int i) {
return (i - 1) / 2; // Integer division down
return (i - 1) / 2; // Floor division
}
/* Start heapifying node i, from bottom to top */
/* Starting from node i, heapify from bottom to top */
void siftUp(int i) {
while (true) {
// Get parent node of node i
int p = parent(i);
// When "crossing the root node" or "node does not need repair", end heapification
// When "crossing root node" or "node needs no repair", end heapify
if (p < 0 || maxHeap[i] <= maxHeap[p])
break;
// Swap two nodes
swap(maxHeap[i], maxHeap[p]);
// Loop upwards heapification
// Loop upward heapify
i = p;
}
}
/* Start heapifying node i, from top to bottom */
/* Starting from node i, heapify from top to bottom */
void siftDown(int i) {
while (true) {
// Determine the largest node among i, l, r, noted as ma
// If node i is largest or indices l, r are out of bounds, no need to continue heapify, break
int l = left(i), r = right(i), ma = i;
if (l < size() && maxHeap[l] > maxHeap[ma])
ma = l;
if (r < size() && maxHeap[r] > maxHeap[ma])
ma = r;
// If node i is the largest or indices l, r are out of bounds, no further heapification needed, break
// Swap two nodes
if (ma == i)
break;
swap(maxHeap[i], maxHeap[ma]);
@@ -63,9 +63,9 @@ class MaxHeap {
public:
/* Constructor, build heap based on input list */
MaxHeap(vector<int> nums) {
// Add all list elements into the heap
// Add list elements to heap as is
maxHeap = nums;
// Heapify all nodes except leaves
// Heapify all nodes except leaf nodes
for (int i = parent(size() - 1); i >= 0; i--) {
siftDown(i);
}
@@ -76,17 +76,17 @@ class MaxHeap {
return maxHeap.size();
}
/* Determine if heap is empty */
/* Check if heap is empty */
bool isEmpty() {
return size() == 0;
}
/* Access heap top element */
/* Access top element */
int peek() {
return maxHeap[0];
}
/* Push the element into heap */
/* Element enters heap */
void push(int val) {
// Add node
maxHeap.push_back(val);
@@ -96,23 +96,23 @@ class MaxHeap {
/* Element exits heap */
void pop() {
// Empty handling
// Handle empty case
if (isEmpty()) {
throw out_of_range("Heap is empty");
}
// Swap the root node with the rightmost leaf node (swap the first element with the last element)
// Delete node
swap(maxHeap[0], maxHeap[size() - 1]);
// Remove node
maxHeap.pop_back();
// Heapify from top to bottom
// Return top element
siftDown(0);
}
/* Print heap (binary tree)*/
/* Driver Code*/
void print() {
cout << "Array representation of the heap:";
cout << "Heap array representation:";
printVector(maxHeap);
cout << "Tree representation of the heap:" << endl;
cout << "Heap tree representation:" << endl;
TreeNode *root = vectorToTree(maxHeap);
printTree(root);
freeMemoryTree(root);
@@ -121,35 +121,35 @@ class MaxHeap {
/* Driver Code */
int main() {
/* Initialize max-heap */
/* Consider negating the elements before entering the heap, which can reverse the size relationship, thus implementing max heap */
vector<int> vec{9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2};
MaxHeap maxHeap(vec);
cout << "\nEnter list and build heap" << endl;
cout << "\nAfter inputting list and building heap" << endl;
maxHeap.print();
/* Access heap top element */
/* Check if heap is empty */
int peek = maxHeap.peek();
cout << "\nTop element of the heap is " << peek << endl;
cout << "\nHeap top element is " << peek << endl;
/* Push the element into heap */
/* Element enters heap */
int val = 7;
maxHeap.push(val);
cout << "\nAfter element " << val << " is added to the heap" << endl;
cout << "\nAfter element " << val << " pushes to heap" << endl;
maxHeap.print();
/* Pop the element at the heap top */
/* Time complexity is O(n), not O(nlogn) */
peek = maxHeap.peek();
maxHeap.pop();
cout << "\nAfter the top element " << peek << " is removed from the heap" << endl;
cout << "\nAfter heap top element " << peek << " pops from heap" << endl;
maxHeap.print();
/* Get heap size */
int size = maxHeap.size();
cout << "\nNumber of elements in the heap is " << size << endl;
cout << "\nHeap size is " << size << endl;
/* Determine if heap is empty */
/* Check if heap is empty */
bool isEmpty = maxHeap.isEmpty();
cout << "\nIs the heap empty " << isEmpty << endl;
cout << "\nIs heap empty " << isEmpty << endl;
return 0;
}
+6 -6
View File
@@ -6,17 +6,17 @@
#include "../utils/common.hpp"
/* Using heap to find the largest k elements in an array */
/* Find the largest k elements in array based on heap */
priority_queue<int, vector<int>, greater<int>> topKHeap(vector<int> &nums, int k) {
// Initialize min-heap
// Python's heapq module implements min heap by default
priority_queue<int, vector<int>, greater<int>> heap;
// Enter the first k elements of the array into the heap
// Enter the first k elements of array into heap
for (int i = 0; i < k; i++) {
heap.push(nums[i]);
}
// From the k+1th element, keep the heap length as k
// Starting from the (k+1)th element, maintain heap length as k
for (int i = k; i < nums.size(); i++) {
// If the current element is larger than the heap top element, remove the heap top element and enter the current element into the heap
// If current element is greater than top element, top element exits heap, current element enters heap
if (nums[i] > heap.top()) {
heap.pop();
heap.push(nums[i]);
@@ -31,7 +31,7 @@ int main() {
int k = 3;
priority_queue<int, vector<int>, greater<int>> res = topKHeap(nums, k);
cout << "The largest " << k << " elements are:";
cout << "The largest " << k << " elements are: ";
printHeap(res);
return 0;
@@ -6,39 +6,39 @@
#include "../utils/common.hpp"
/* Binary search (double closed interval) */
/* Binary search (closed interval on both sides) */
int binarySearch(vector<int> &nums, int target) {
// Initialize double closed interval [0, n-1], i.e., i, j point to the first element and last element of the array respectively
// Initialize closed interval [0, n-1], i.e., i, j point to the first and last elements of the array
int i = 0, j = nums.size() - 1;
// Loop until the search interval is empty (when i > j, it is empty)
// Loop, exit when the search interval is empty (empty when i > j)
while (i <= j) {
int m = i + (j - i) / 2; // Calculate midpoint index m
if (nums[m] < target) // This situation indicates that target is in the interval [m+1, j]
int m = i + (j - i) / 2; // Calculate the midpoint index m
if (nums[m] < target) // This means target is in the interval [m+1, j]
i = m + 1;
else if (nums[m] > target) // This situation indicates that target is in the interval [i, m-1]
else if (nums[m] > target) // This means target is in the interval [i, m-1]
j = m - 1;
else // Found the target element, thus return its index
else // Found the target element, return its index
return m;
}
// Did not find the target element, thus return -1
// Target element not found, return -1
return -1;
}
/* Binary search (left closed right open interval) */
/* Binary search (left-closed right-open interval) */
int binarySearchLCRO(vector<int> &nums, int target) {
// Initialize left closed right open interval [0, n), i.e., i, j point to the first element and the last element +1 of the array respectively
// Initialize left-closed right-open interval [0, n), i.e., i, j point to the first element and last element+1
int i = 0, j = nums.size();
// Loop until the search interval is empty (when i = j, it is empty)
// Loop, exit when the search interval is empty (empty when i = j)
while (i < j) {
int m = i + (j - i) / 2; // Calculate midpoint index m
if (nums[m] < target) // This situation indicates that target is in the interval [m+1, j)
int m = i + (j - i) / 2; // Calculate the midpoint index m
if (nums[m] < target) // This means target is in the interval [m+1, j)
i = m + 1;
else if (nums[m] > target) // This situation indicates that target is in the interval [i, m)
else if (nums[m] > target) // This means target is in the interval [i, m)
j = m;
else // Found the target element, thus return its index
else // Found the target element, return its index
return m;
}
// Did not find the target element, thus return -1
// Target element not found, return -1
return -1;
}
@@ -47,13 +47,13 @@ int main() {
int target = 6;
vector<int> nums = {1, 3, 6, 8, 12, 15, 23, 26, 31, 35};
/* Binary search (double closed interval) */
/* Binary search (closed interval on both sides) */
int index = binarySearch(nums, target);
cout << "Index of target element 6 =" << index << endl;
cout << "Index of target element 6 = " << index << endl;
/* Binary search (left closed right open interval) */
/* Binary search (left-closed right-open interval) */
index = binarySearchLCRO(nums, target);
cout << "Index of target element 6 =" << index << endl;
cout << "Index of target element 6 = " << index << endl;
return 0;
}
@@ -8,13 +8,13 @@
/* Binary search for insertion point (with duplicate elements) */
int binarySearchInsertion(const vector<int> &nums, int target) {
int i = 0, j = nums.size() - 1; // Initialize double closed interval [0, n-1]
int i = 0, j = nums.size() - 1; // Initialize closed interval [0, n-1]
while (i <= j) {
int m = i + (j - i) / 2; // Calculate midpoint index m
int m = i + (j - i) / 2; // Calculate the midpoint index m
if (nums[m] < target) {
i = m + 1; // Target is in interval [m+1, j]
i = m + 1; // target is in the interval [m+1, j]
} else {
j = m - 1; // First element less than target is in interval [i, m-1]
j = m - 1; // The first element less than target is in the interval [i, m-1]
}
}
// Return insertion point i
@@ -25,7 +25,7 @@ int binarySearchInsertion(const vector<int> &nums, int target) {
int binarySearchLeftEdge(vector<int> &nums, int target) {
// Equivalent to finding the insertion point of target
int i = binarySearchInsertion(nums, target);
// Did not find target, thus return -1
// Target not found, return -1
if (i == nums.size() || nums[i] != target) {
return -1;
}
@@ -39,7 +39,7 @@ int binarySearchRightEdge(vector<int> &nums, int target) {
int i = binarySearchInsertion(nums, target + 1);
// j points to the rightmost target, i points to the first element greater than target
int j = i - 1;
// Did not find target, thus return -1
// Target not found, return -1
if (j == -1 || nums[j] != target) {
return -1;
}
@@ -54,12 +54,12 @@ int main() {
cout << "\nArray nums = ";
printVector(nums);
// Binary search for left and right boundaries
// Binary search left and right boundaries
for (int target : {6, 7}) {
int index = binarySearchLeftEdge(nums, target);
cout << "The leftmost index of element " << target << " is " << index << endl;
cout << "Index of leftmost element " << target << " is " << index << endl;
index = binarySearchRightEdge(nums, target);
cout << "The rightmost index of element " << target << " is " << index << endl;
cout << "Index of rightmost element " << target << " is " << index << endl;
}
return 0;
@@ -8,32 +8,32 @@
/* Binary search for insertion point (no duplicate elements) */
int binarySearchInsertionSimple(vector<int> &nums, int target) {
int i = 0, j = nums.size() - 1; // Initialize double closed interval [0, n-1]
int i = 0, j = nums.size() - 1; // Initialize closed interval [0, n-1]
while (i <= j) {
int m = i + (j - i) / 2; // Calculate midpoint index m
int m = i + (j - i) / 2; // Calculate the midpoint index m
if (nums[m] < target) {
i = m + 1; // Target is in interval [m+1, j]
i = m + 1; // target is in the interval [m+1, j]
} else if (nums[m] > target) {
j = m - 1; // Target is in interval [i, m-1]
j = m - 1; // target is in the interval [i, m-1]
} else {
return m; // Found target, return insertion point m
}
}
// Did not find target, return insertion point i
// Target not found, return insertion point i
return i;
}
/* Binary search for insertion point (with duplicate elements) */
int binarySearchInsertion(vector<int> &nums, int target) {
int i = 0, j = nums.size() - 1; // Initialize double closed interval [0, n-1]
int i = 0, j = nums.size() - 1; // Initialize closed interval [0, n-1]
while (i <= j) {
int m = i + (j - i) / 2; // Calculate midpoint index m
int m = i + (j - i) / 2; // Calculate the midpoint index m
if (nums[m] < target) {
i = m + 1; // Target is in interval [m+1, j]
i = m + 1; // target is in the interval [m+1, j]
} else if (nums[m] > target) {
j = m - 1; // Target is in interval [i, m-1]
j = m - 1; // target is in the interval [i, m-1]
} else {
j = m - 1; // First element less than target is in interval [i, m-1]
j = m - 1; // The first element less than target is in the interval [i, m-1]
}
}
// Return insertion point i
@@ -49,7 +49,7 @@ int main() {
// Binary search for insertion point
for (int target : {6, 9}) {
int index = binarySearchInsertionSimple(nums, target);
cout << "The insertion point index for element " << target << " is " << index << endl;
cout << "Insertion point index for element " << target << " is " << index << endl;
}
// Array with duplicate elements
@@ -59,7 +59,7 @@ int main() {
// Binary search for insertion point
for (int target : {2, 6, 20}) {
int index = binarySearchInsertion(nums, target);
cout << "The insertion point index for element " << target << " is " << index << endl;
cout << "Insertion point index for element " << target << " is " << index << endl;
}
return 0;
@@ -9,7 +9,7 @@
/* Hash search (array) */
int hashingSearchArray(unordered_map<int, int> map, int target) {
// Hash table's key: target element, value: index
// If the hash table does not contain this key, return -1
// If this key does not exist in the hash table, return -1
if (map.find(target) == map.end())
return -1;
return map[target];
@@ -18,7 +18,7 @@ int hashingSearchArray(unordered_map<int, int> map, int target) {
/* Hash search (linked list) */
ListNode *hashingSearchLinkedList(unordered_map<int, ListNode *> map, int target) {
// Hash table key: target node value, value: node object
// If the key is not in the hash table, return nullptr
// Return nullptr if key does not exist in hash table
if (map.find(target) == map.end())
return nullptr;
return map[target];
@@ -36,7 +36,7 @@ int main() {
map[nums[i]] = i; // key: element, value: index
}
int index = hashingSearchArray(map, target);
cout << "The index of target element 3 is " << index << endl;
cout << "Index of target element 3 = " << index << endl;
/* Hash search (linked list) */
ListNode *head = vecToLinkedList(nums);
@@ -47,7 +47,7 @@ int main() {
head = head->next;
}
ListNode *node = hashingSearchLinkedList(map1, target);
cout << "The corresponding node object for target node value 3 is " << node << endl;
cout << "Node object corresponding to target node value 3 is " << node << endl;
return 0;
}
@@ -10,24 +10,24 @@
int linearSearchArray(vector<int> &nums, int target) {
// Traverse array
for (int i = 0; i < nums.size(); i++) {
// Found the target element, thus return its index
// Found the target element, return its index
if (nums[i] == target)
return i;
}
// Did not find the target element, thus return -1
// Target element not found, return -1
return -1;
}
/* Linear search (linked list) */
ListNode *linearSearchLinkedList(ListNode *head, int target) {
// Traverse the list
// Traverse the linked list
while (head != nullptr) {
// Found the target node, return it
if (head->val == target)
return head;
head = head->next;
}
// If the target node is not found, return nullptr
// Target node not found, return nullptr
return nullptr;
}
@@ -38,12 +38,12 @@ int main() {
/* Perform linear search in array */
vector<int> nums = {1, 5, 3, 2, 4, 7, 5, 9, 10, 8};
int index = linearSearchArray(nums, target);
cout << "The index of target element 3 is " << index << endl;
cout << "Index of target element 3 = " << index << endl;
/* Perform linear search in linked list */
ListNode *head = vecToLinkedList(nums);
ListNode *node = linearSearchLinkedList(head, target);
cout << "The corresponding node object for target node value 3 is " << node << endl;
cout << "Node object corresponding to target node value 3 is " << node << endl;
return 0;
}
+8 -8
View File
@@ -6,10 +6,10 @@
#include "../utils/common.hpp"
/* Method one: Brute force enumeration */
/* Method 1: Brute force enumeration */
vector<int> twoSumBruteForce(vector<int> &nums, int target) {
int size = nums.size();
// Two-layer loop, time complexity is O(n^2)
// Two nested loops, time complexity is O(n^2)
for (int i = 0; i < size - 1; i++) {
for (int j = i + 1; j < size; j++) {
if (nums[i] + nums[j] == target)
@@ -19,12 +19,12 @@ vector<int> twoSumBruteForce(vector<int> &nums, int target) {
return {};
}
/* Method two: Auxiliary hash table */
/* Method 2: Auxiliary hash table */
vector<int> twoSumHashTable(vector<int> &nums, int target) {
int size = nums.size();
// Auxiliary hash table, space complexity is O(n)
unordered_map<int, int> dic;
// Single-layer loop, time complexity is O(n)
// Single loop, time complexity is O(n)
for (int i = 0; i < size; i++) {
if (dic.find(target - nums[i]) != dic.end()) {
return {dic[target - nums[i]], i};
@@ -41,13 +41,13 @@ int main() {
int target = 13;
// ====== Driver Code ======
// Method one
// Method 1
vector<int> res = twoSumBruteForce(nums, target);
cout << "Method one res = ";
cout << "Method 1 res = ";
printVector(res);
// Method two
// Method 2
res = twoSumHashTable(nums, target);
cout << "Method two res = ";
cout << "Method 2 res = ";
printVector(res);
return 0;
+9 -9
View File
@@ -10,33 +10,33 @@
void bubbleSort(vector<int> &nums) {
// Outer loop: unsorted range is [0, i]
for (int i = nums.size() - 1; i > 0; i--) {
// Inner loop: swap the largest element in the unsorted range [0, i] to the right end of the range
// Inner loop: swap the largest element in the unsorted range [0, i] to the rightmost end of that range
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// Swap nums[j] and nums[j + 1]
// Here, the std
// Using std::swap() function here
swap(nums[j], nums[j + 1]);
}
}
}
}
/* Bubble sort (optimized with flag)*/
/* Bubble sort (flag optimization)*/
void bubbleSortWithFlag(vector<int> &nums) {
// Outer loop: unsorted range is [0, i]
for (int i = nums.size() - 1; i > 0; i--) {
bool flag = false; // Initialize flag
// Inner loop: swap the largest element in the unsorted range [0, i] to the right end of the range
// Inner loop: swap the largest element in the unsorted range [0, i] to the rightmost end of that range
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// Swap nums[j] and nums[j + 1]
// Here, the std
// Using std::swap() function here
swap(nums[j], nums[j + 1]);
flag = true; // Record swapped elements
flag = true; // Record element swap
}
}
if (!flag)
break; // If no elements were swapped in this round of "bubbling", exit
break; // No elements were swapped in this round of "bubbling", exit directly
}
}
@@ -44,12 +44,12 @@ void bubbleSortWithFlag(vector<int> &nums) {
int main() {
vector<int> nums = {4, 1, 3, 1, 5, 2};
bubbleSort(nums);
cout << "After bubble sort, nums = ";
cout << "After bubble sort completes, nums = ";
printVector(nums);
vector<int> nums1 = {4, 1, 3, 1, 5, 2};
bubbleSortWithFlag(nums1);
cout << "After bubble sort, nums1 = ";
cout << "After bubble sort completes, nums1 = ";
printVector(nums1);
return 0;
+3 -3
View File
@@ -15,7 +15,7 @@ void bucketSort(vector<float> &nums) {
for (float num : nums) {
// Input data range is [0, 1), use num * k to map to index range [0, k-1]
int i = num * k;
// Add number to bucket_idx
// Add num to bucket bucket_idx
buckets[i].push_back(num);
}
// 2. Sort each bucket
@@ -34,10 +34,10 @@ void bucketSort(vector<float> &nums) {
/* Driver Code */
int main() {
// Assume input data is floating point, range [0, 1)
// Assume input data is floating point, interval [0, 1)
vector<float> nums = {0.49f, 0.96f, 0.82f, 0.09f, 0.57f, 0.43f, 0.91f, 0.75f, 0.15f, 0.37f};
bucketSort(nums);
cout << "After bucket sort, nums = ";
cout << "After bucket sort completes, nums = ";
printVector(nums);
return 0;
@@ -14,7 +14,7 @@ void countingSortNaive(vector<int> &nums) {
for (int num : nums) {
m = max(m, num);
}
// 2. Count the occurrence of each digit
// 2. Count the occurrence of each number
// counter[num] represents the occurrence of num
vector<int> counter(m + 1, 0);
for (int num : nums) {
@@ -37,7 +37,7 @@ void countingSort(vector<int> &nums) {
for (int num : nums) {
m = max(m, num);
}
// 2. Count the occurrence of each digit
// 2. Count the occurrence of each number
// counter[num] represents the occurrence of num
vector<int> counter(m + 1, 0);
for (int num : nums) {
@@ -65,12 +65,12 @@ void countingSort(vector<int> &nums) {
int main() {
vector<int> nums = {1, 0, 1, 2, 0, 4, 0, 2, 2, 4};
countingSortNaive(nums);
cout << "After count sort (unable to sort objects), nums = ";
cout << "After counting sort (cannot sort objects) completes, nums = ";
printVector(nums);
vector<int> nums1 = {1, 0, 1, 2, 0, 4, 0, 2, 2, 4};
countingSort(nums1);
cout << "After count sort, nums1 = ";
cout << "After counting sort completes, nums1 = ";
printVector(nums1);
return 0;
+4 -4
View File
@@ -9,7 +9,7 @@
/* Heap length is n, start heapifying node i, from top to bottom */
void siftDown(vector<int> &nums, int n, int i) {
while (true) {
// Determine the largest node among i, l, r, noted as ma
// If node i is largest or indices l, r are out of bounds, no need to continue heapify, break
int l = 2 * i + 1;
int r = 2 * i + 2;
int ma = i;
@@ -17,7 +17,7 @@ void siftDown(vector<int> &nums, int n, int i) {
ma = l;
if (r < n && nums[r] > nums[ma])
ma = r;
// If node i is the largest or indices l, r are out of bounds, no further heapification needed, break
// Swap two nodes
if (ma == i) {
break;
}
@@ -36,7 +36,7 @@ void heapSort(vector<int> &nums) {
}
// Extract the largest element from the heap and repeat for n-1 rounds
for (int i = nums.size() - 1; i > 0; --i) {
// Swap the root node with the rightmost leaf node (swap the first element with the last element)
// Delete node
swap(nums[0], nums[i]);
// Start heapifying the root node, from top to bottom
siftDown(nums, i, 0);
@@ -47,7 +47,7 @@ void heapSort(vector<int> &nums) {
int main() {
vector<int> nums = {4, 1, 3, 1, 5, 2};
heapSort(nums);
cout << "After heap sort, nums = ";
cout << "After heap sort completes, nums = ";
printVector(nums);
return 0;
@@ -8,10 +8,10 @@
/* Insertion sort */
void insertionSort(vector<int> &nums) {
// Outer loop: sorted range is [0, i-1]
// Outer loop: sorted interval is [0, i-1]
for (int i = 1; i < nums.size(); i++) {
int base = nums[i], j = i - 1;
// Inner loop: insert base into the correct position within the sorted range [0, i-1]
// Inner loop: insert base into the correct position within the sorted interval [0, i-1]
while (j >= 0 && nums[j] > base) {
nums[j + 1] = nums[j]; // Move nums[j] to the right by one position
j--;
@@ -24,7 +24,7 @@ void insertionSort(vector<int> &nums) {
int main() {
vector<int> nums = {4, 1, 3, 1, 5, 2};
insertionSort(nums);
cout << "After insertion sort, nums = ";
cout << "After insertion sort completes, nums = ";
printVector(nums);
return 0;
+2 -2
View File
@@ -38,7 +38,7 @@ void mergeSort(vector<int> &nums, int left, int right) {
// Termination condition
if (left >= right)
return; // Terminate recursion when subarray length is 1
// Partition stage
// Divide and conquer stage
int mid = left + (right - left) / 2; // Calculate midpoint
mergeSort(nums, left, mid); // Recursively process the left subarray
mergeSort(nums, mid + 1, right); // Recursively process the right subarray
@@ -51,7 +51,7 @@ int main() {
/* Merge sort */
vector<int> nums = {7, 3, 2, 6, 0, 1, 5, 4};
mergeSort(nums, 0, nums.size() - 1);
cout << "After merge sort, nums = ";
cout << "After merge sort completes, nums = ";
printVector(nums);
return 0;
+29 -50
View File
@@ -9,26 +9,19 @@
/* Quick sort class */
class QuickSort {
private:
/* Swap elements */
static void swap(vector<int> &nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
/* Partition */
/* Sentinel partition */
static int partition(vector<int> &nums, int left, int right) {
// Use nums[left] as the pivot
int i = left, j = right;
while (i < j) {
while (i < j && nums[j] >= nums[left])
j--; // Search from right to left for the first element smaller than the pivot
j--; // Search from right to left for the first element smaller than the pivot
while (i < j && nums[i] <= nums[left])
i++; // Search from left to right for the first element greater than the pivot
swap(nums, i, j); // Swap these two elements
i++; // Search from left to right for the first element greater than the pivot
swap(nums[i], nums[j]); // Swap these two elements
}
swap(nums, i, left); // Swap the pivot to the boundary between the two subarrays
return i; // Return the index of the pivot
swap(nums[i], nums[left]); // Swap the pivot to the boundary between the two subarrays
return i; // Return the index of the pivot
}
public:
@@ -37,7 +30,7 @@ class QuickSort {
// Terminate recursion when subarray length is 1
if (left >= right)
return;
// Partition
// Sentinel partition
int pivot = partition(nums, left, right);
// Recursively process the left subarray and right subarray
quickSort(nums, left, pivot - 1);
@@ -48,13 +41,6 @@ class QuickSort {
/* Quick sort class (median pivot optimization) */
class QuickSortMedian {
private:
/* Swap elements */
static void swap(vector<int> &nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
/* Select the median of three candidate elements */
static int medianThree(vector<int> &nums, int left, int mid, int right) {
int l = nums[left], m = nums[mid], r = nums[right];
@@ -65,23 +51,23 @@ class QuickSortMedian {
return right;
}
/* Partition (median of three) */
/* Sentinel partition (median of three) */
static int partition(vector<int> &nums, int left, int right) {
// Select the median of three candidate elements
int med = medianThree(nums, left, (left + right) / 2, right);
// Swap the median to the array's leftmost position
swap(nums, left, med);
swap(nums[left], nums[med]);
// Use nums[left] as the pivot
int i = left, j = right;
while (i < j) {
while (i < j && nums[j] >= nums[left])
j--; // Search from right to left for the first element smaller than the pivot
j--; // Search from right to left for the first element smaller than the pivot
while (i < j && nums[i] <= nums[left])
i++; // Search from left to right for the first element greater than the pivot
swap(nums, i, j); // Swap these two elements
i++; // Search from left to right for the first element greater than the pivot
swap(nums[i], nums[j]); // Swap these two elements
}
swap(nums, i, left); // Swap the pivot to the boundary between the two subarrays
return i; // Return the index of the pivot
swap(nums[i], nums[left]); // Swap the pivot to the boundary between the two subarrays
return i; // Return the index of the pivot
}
public:
@@ -90,7 +76,7 @@ class QuickSortMedian {
// Terminate recursion when subarray length is 1
if (left >= right)
return;
// Partition
// Sentinel partition
int pivot = partition(nums, left, right);
// Recursively process the left subarray and right subarray
quickSort(nums, left, pivot - 1);
@@ -98,37 +84,30 @@ class QuickSortMedian {
}
};
/* Quick sort class (tail recursion optimization) */
/* Quick sort class (recursion depth optimization) */
class QuickSortTailCall {
private:
/* Swap elements */
static void swap(vector<int> &nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
/* Partition */
/* Sentinel partition */
static int partition(vector<int> &nums, int left, int right) {
// Use nums[left] as the pivot
int i = left, j = right;
while (i < j) {
while (i < j && nums[j] >= nums[left])
j--; // Search from right to left for the first element smaller than the pivot
j--; // Search from right to left for the first element smaller than the pivot
while (i < j && nums[i] <= nums[left])
i++; // Search from left to right for the first element greater than the pivot
swap(nums, i, j); // Swap these two elements
i++; // Search from left to right for the first element greater than the pivot
swap(nums[i], nums[j]); // Swap these two elements
}
swap(nums, i, left); // Swap the pivot to the boundary between the two subarrays
return i; // Return the index of the pivot
swap(nums[i], nums[left]); // Swap the pivot to the boundary between the two subarrays
return i; // Return the index of the pivot
}
public:
/* Quick sort (tail recursion optimization) */
/* Quick sort (recursion depth optimization) */
static void quickSort(vector<int> &nums, int left, int right) {
// Terminate when subarray length is 1
while (left < right) {
// Partition operation
// Sentinel partition operation
int pivot = partition(nums, left, right);
// Perform quick sort on the shorter of the two subarrays
if (pivot - left < right - pivot) {
@@ -147,19 +126,19 @@ int main() {
/* Quick sort */
vector<int> nums{2, 4, 1, 0, 3, 5};
QuickSort::quickSort(nums, 0, nums.size() - 1);
cout << "After quick sort, nums = ";
cout << "After quick sort completes, nums = ";
printVector(nums);
/* Quick sort (median pivot optimization) */
/* Quick sort (recursion depth optimization) */
vector<int> nums1 = {2, 4, 1, 0, 3, 5};
QuickSortMedian::quickSort(nums1, 0, nums1.size() - 1);
cout << "Quick sort (median pivot optimization) completed, nums = ";
cout << "After quick sort (median pivot optimization), nums = ";
printVector(nums1);
/* Quick sort (tail recursion optimization) */
/* Quick sort (recursion depth optimization) */
vector<int> nums2 = {2, 4, 1, 0, 3, 5};
QuickSortTailCall::quickSort(nums2, 0, nums2.size() - 1);
cout << "Quick sort (tail recursion optimization) completed, nums = ";
cout << "After quick sort (recursion depth optimization), nums = ";
printVector(nums2);
return 0;
+1 -1
View File
@@ -58,7 +58,7 @@ int main() {
vector<int> nums = {10546151, 35663510, 42865989, 34862445, 81883077,
88906420, 72429244, 30524779, 82060337, 63832996};
radixSort(nums);
cout << "After radix sort, nums = ";
cout << "After radix sort completes, nums = ";
printVector(nums);
return 0;
@@ -9,15 +9,15 @@
/* Selection sort */
void selectionSort(vector<int> &nums) {
int n = nums.size();
// Outer loop: unsorted range is [i, n-1]
// Outer loop: unsorted interval is [i, n-1]
for (int i = 0; i < n - 1; i++) {
// Inner loop: find the smallest element within the unsorted range
// Inner loop: find the smallest element within the unsorted interval
int k = i;
for (int j = i + 1; j < n; j++) {
if (nums[j] < nums[k])
k = j; // Record the index of the smallest element
}
// Swap the smallest element with the first element of the unsorted range
// Swap the smallest element with the first element of the unsorted interval
swap(nums[i], nums[k]);
}
}
@@ -27,7 +27,7 @@ int main() {
vector<int> nums = {4, 1, 3, 1, 5, 2};
selectionSort(nums);
cout << "After selection sort, nums = ";
cout << "After selection sort completes, nums = ";
printVector(nums);
return 0;
@@ -6,12 +6,12 @@
#include "../utils/common.hpp"
/* Double-ended queue class based on circular array */
/* Double-ended queue based on circular array implementation */
class ArrayDeque {
private:
vector<int> nums; // Array used to store elements of the double-ended queue
int front; // Front pointer, pointing to the front element
int queSize; // Length of the double-ended queue
vector<int> nums; // Array for storing double-ended queue elements
int front; // Front pointer, points to the front of the queue element
int queSize; // Double-ended queue length
public:
/* Constructor */
@@ -30,81 +30,81 @@ class ArrayDeque {
return queSize;
}
/* Determine if the double-ended queue is empty */
/* Check if the double-ended queue is empty */
bool isEmpty() {
return queSize == 0;
}
/* Calculate circular array index */
int index(int i) {
// Implement circular array by modulo operation
// When i exceeds the tail of the array, return to the head
// When i exceeds the head of the array, return to the tail
// Use modulo operation to wrap the array head and tail together
// When i passes the tail of the array, return to the head
// When i passes the head of the array, return to the tail
return (i + capacity()) % capacity();
}
/* Front enqueue */
/* Front of the queue enqueue */
void pushFirst(int num) {
if (queSize == capacity()) {
cout << "Double-ended queue is full" << endl;
return;
}
// Move the front pointer one position to the left
// Implement front crossing the head of the array to return to the tail by modulo operation
// Use modulo operation to wrap front around to the tail after passing the head of the array
// Add num to the front of the queue
front = index(front - 1);
// Add num to the front
// Add num to front of queue
nums[front] = num;
queSize++;
}
/* Rear enqueue */
/* Rear of the queue enqueue */
void pushLast(int num) {
if (queSize == capacity()) {
cout << "Double-ended queue is full" << endl;
return;
}
// Calculate rear pointer, pointing to rear index + 1
// Use modulo operation to wrap rear around to the head after passing the tail of the array
int rear = index(front + queSize);
// Add num to the rear
// Front pointer moves one position backward
nums[rear] = num;
queSize++;
}
/* Front dequeue */
/* Rear of the queue dequeue */
int popFirst() {
int num = peekFirst();
// Move front pointer one position backward
// Move front pointer backward by one position
front = index(front + 1);
queSize--;
return num;
}
/* Rear dequeue */
/* Access rear of the queue element */
int popLast() {
int num = peekLast();
queSize--;
return num;
}
/* Access front element */
/* Return list for printing */
int peekFirst() {
if (isEmpty())
throw out_of_range("Double-ended queue is empty");
throw out_of_range("Deque is empty");
return nums[front];
}
/* Access rear element */
/* Driver Code */
int peekLast() {
if (isEmpty())
throw out_of_range("Double-ended queue is empty");
// Calculate rear element index
throw out_of_range("Deque is empty");
// Initialize double-ended queue
int last = index(front + queSize - 1);
return nums[last];
}
/* Return array for printing */
vector<int> toVector() {
// Only convert elements within valid length range
// Elements enqueue
vector<int> res(queSize);
for (int i = 0, j = front; i < queSize; i++, j++) {
res[i] = nums[index(j)];
@@ -115,7 +115,7 @@ class ArrayDeque {
/* Driver Code */
int main() {
/* Initialize double-ended queue */
/* Get the length of the double-ended queue */
ArrayDeque *deque = new ArrayDeque(10);
deque->pushLast(3);
deque->pushLast(2);
@@ -123,34 +123,34 @@ int main() {
cout << "Double-ended queue deque = ";
printVector(deque->toVector());
/* Access element */
/* Update element */
int peekFirst = deque->peekFirst();
cout << "Front element peekFirst = " << peekFirst << endl;
int peekLast = deque->peekLast();
cout << "Back element peekLast = " << peekLast << endl;
cout << "Rear element peekLast = " << peekLast << endl;
/* Element enqueue */
/* Elements enqueue */
deque->pushLast(4);
cout << "Element 4 enqueued at the tail, deque = ";
cout << "After element 4 enqueues at rear, deque = ";
printVector(deque->toVector());
deque->pushFirst(1);
cout << "Element 1 enqueued at the head, deque = ";
cout << "After element 1 enqueues at front, deque = ";
printVector(deque->toVector());
/* Element dequeue */
int popLast = deque->popLast();
cout << "Deque tail element = " << popLast << ", after dequeuing from the tail";
cout << "Rear dequeue element = " << popLast << ", after rear dequeue, deque = ";
printVector(deque->toVector());
int popFirst = deque->popFirst();
cout << "Deque front element = " << popFirst << ", after dequeuing from the front";
cout << "Front dequeue element = " << popFirst << ", after front dequeue, deque = ";
printVector(deque->toVector());
/* Get the length of the double-ended queue */
int size = deque->size();
cout << "Length of the double-ended queue size = " << size << endl;
cout << "Double-ended queue length size = " << size << endl;
/* Determine if the double-ended queue is empty */
/* Check if the double-ended queue is empty */
bool isEmpty = deque->isEmpty();
cout << "Is the double-ended queue empty = " << boolalpha << isEmpty << endl;
cout << "Double-ended queue is empty = " << boolalpha << isEmpty << endl;
return 0;
}
@@ -6,17 +6,17 @@
#include "../utils/common.hpp"
/* Queue class based on circular array */
/* Queue based on circular array implementation */
class ArrayQueue {
private:
int *nums; // Array for storing queue elements
int front; // Front pointer, pointing to the front element
int front; // Front pointer, points to the front of the queue element
int queSize; // Queue length
int queCapacity; // Queue capacity
public:
ArrayQueue(int capacity) {
// Initialize an array
// Initialize array
nums = new int[capacity];
queCapacity = capacity;
front = queSize = 0;
@@ -36,7 +36,7 @@ class ArrayQueue {
return queSize;
}
/* Determine if the queue is empty */
/* Check if the queue is empty */
bool isEmpty() {
return size() == 0;
}
@@ -47,10 +47,10 @@ class ArrayQueue {
cout << "Queue is full" << endl;
return;
}
// Calculate rear pointer, pointing to rear index + 1
// Use modulo operation to wrap the rear pointer from the end of the array back to the start
// Use modulo operation to wrap rear around to the head after passing the tail of the array
// Add num to the rear of the queue
int rear = (front + queSize) % queCapacity;
// Add num to the rear
// Front pointer moves one position backward
nums[rear] = num;
queSize++;
}
@@ -58,13 +58,13 @@ class ArrayQueue {
/* Dequeue */
int pop() {
int num = peek();
// Move front pointer one position backward, returning to the head of the array if it exceeds the tail
// Move front pointer backward by one position, if it passes the tail, return to array head
front = (front + 1) % queCapacity;
queSize--;
return num;
}
/* Access front element */
/* Return list for printing */
int peek() {
if (isEmpty())
throw out_of_range("Queue is empty");
@@ -73,7 +73,7 @@ class ArrayQueue {
/* Convert array to Vector and return */
vector<int> toVector() {
// Only convert elements within valid length range
// Elements enqueue
vector<int> arr(queSize);
for (int i = 0, j = front; i < queSize; i++, j++) {
arr[i] = nums[j % queCapacity];
@@ -84,11 +84,11 @@ class ArrayQueue {
/* Driver Code */
int main() {
/* Initialize queue */
/* Access front of the queue element */
int capacity = 10;
ArrayQueue *queue = new ArrayQueue(capacity);
/* Element enqueue */
/* Elements enqueue */
queue->push(1);
queue->push(3);
queue->push(2);
@@ -97,28 +97,28 @@ int main() {
cout << "Queue queue = ";
printVector(queue->toVector());
/* Access front element */
/* Return list for printing */
int peek = queue->peek();
cout << "Front element peek = " << peek << endl;
/* Element dequeue */
peek = queue->pop();
cout << "Element dequeued = " << peek << ", after dequeuing";
cout << "Dequeue element pop = " << peek << ", after dequeue, queue = ";
printVector(queue->toVector());
/* Get the length of the queue */
int size = queue->size();
cout << "Length of the queue size = " << size << endl;
cout << "Queue length size = " << size << endl;
/* Determine if the queue is empty */
/* Check if the queue is empty */
bool empty = queue->isEmpty();
cout << "Is the queue empty = " << empty << endl;
cout << "Queue is empty = " << empty << endl;
/* Test circular array */
for (int i = 0; i < 10; i++) {
queue->push(i);
queue->pop();
cout << "After the " << i << "th round of enqueueing + dequeuing, queue = ";
cout << "After round " << i << " enqueue + dequeue, queue = ";
printVector(queue->toVector());
}
@@ -6,7 +6,7 @@
#include "../utils/common.hpp"
/* Stack class based on array */
/* Stack based on array implementation */
class ArrayStack {
private:
vector<int> stack;
@@ -17,7 +17,7 @@ class ArrayStack {
return stack.size();
}
/* Determine if the stack is empty */
/* Check if the stack is empty */
bool isEmpty() {
return stack.size() == 0;
}
@@ -34,7 +34,7 @@ class ArrayStack {
return num;
}
/* Access stack top element */
/* Return list for printing */
int top() {
if (isEmpty())
throw out_of_range("Stack is empty");
@@ -49,10 +49,10 @@ class ArrayStack {
/* Driver Code */
int main() {
/* Initialize stack */
/* Access top of the stack element */
ArrayStack *stack = new ArrayStack();
/* Element push */
/* Elements push onto stack */
stack->push(1);
stack->push(3);
stack->push(2);
@@ -61,22 +61,22 @@ int main() {
cout << "Stack stack = ";
printVector(stack->toVector());
/* Access stack top element */
/* Return list for printing */
int top = stack->top();
cout << "Top element of the stack top = " << top << endl;
cout << "Stack top element top = " << top << endl;
/* Element pop */
/* Element pop from stack */
top = stack->pop();
cout << "Element popped from the stack = " << top << ", after popping";
cout << "Pop element pop = " << top << ", after pop, stack = ";
printVector(stack->toVector());
/* Get the length of the stack */
int size = stack->size();
cout << "Length of the stack size = " << size << endl;
cout << "Stack length size = " << size << endl;
/* Determine if it's empty */
/* Check if empty */
bool empty = stack->isEmpty();
cout << "Is the stack empty = " << empty << endl;
cout << "Stack is empty = " << empty << endl;
// Free memory
delete stack;
+10 -10
View File
@@ -8,10 +8,10 @@
/* Driver Code */
int main() {
/* Initialize double-ended queue */
/* Get the length of the double-ended queue */
deque<int> deque;
/* Element enqueue */
/* Elements enqueue */
deque.push_back(2);
deque.push_back(5);
deque.push_back(4);
@@ -20,27 +20,27 @@ int main() {
cout << "Double-ended queue deque = ";
printDeque(deque);
/* Access element */
/* Update element */
int front = deque.front();
cout << "Front element of the queue front = " << front << endl;
cout << "Front element front = " << front << endl;
int back = deque.back();
cout << "Back element of the queue back = " << back << endl;
cout << "Back element back = " << back << endl;
/* Element dequeue */
deque.pop_front();
cout << "Front element dequeued = " << front << ", after dequeuing from the front";
cout << "Front dequeue element popFront = " << front << ", after front dequeue, deque = ";
printDeque(deque);
deque.pop_back();
cout << "Back element dequeued = " << back << ", after dequeuing from the back";
cout << "Rear dequeue element popLast = " << back << ", after rear dequeue, deque = ";
printDeque(deque);
/* Get the length of the double-ended queue */
int size = deque.size();
cout << "Length of the double-ended queue size = " << size << endl;
cout << "Double-ended queue length size = " << size << endl;
/* Determine if the double-ended queue is empty */
/* Check if the double-ended queue is empty */
bool empty = deque.empty();
cout << "Is the double-ended queue empty = " << empty << endl;
cout << "Double-ended queue is empty = " << empty << endl;
return 0;
}
@@ -6,19 +6,19 @@
#include "../utils/common.hpp"
/* Double-linked list node */
/* Doubly linked list node */
struct DoublyListNode {
int val; // Node value
DoublyListNode *next; // Pointer to successor node
DoublyListNode *prev; // Pointer to predecessor node
DoublyListNode *next; // Successor node pointer
DoublyListNode *prev; // Predecessor node pointer
DoublyListNode(int val) : val(val), prev(nullptr), next(nullptr) {
}
};
/* Double-ended queue class based on double-linked list */
/* Double-ended queue based on doubly linked list implementation */
class LinkedListDeque {
private:
DoublyListNode *front, *rear; // Front node front, back node rear
DoublyListNode *front, *rear; // Head node front, tail node rear
int queSize = 0; // Length of the double-ended queue
public:
@@ -28,7 +28,7 @@ class LinkedListDeque {
/* Destructor */
~LinkedListDeque() {
// Traverse the linked list, remove nodes, free memory
// Traverse linked list to delete nodes and free memory
DoublyListNode *pre, *cur = front;
while (cur != nullptr) {
pre = cur;
@@ -42,7 +42,7 @@ class LinkedListDeque {
return queSize;
}
/* Determine if the double-ended queue is empty */
/* Check if the double-ended queue is empty */
bool isEmpty() {
return size() == 0;
}
@@ -50,18 +50,18 @@ class LinkedListDeque {
/* Enqueue operation */
void push(int num, bool isFront) {
DoublyListNode *node = new DoublyListNode(num);
// If the list is empty, make front and rear both point to node
// If the linked list is empty, make both front and rear point to node
if (isEmpty())
front = rear = node;
// Front enqueue operation
// Front of the queue enqueue operation
else if (isFront) {
// Add node to the head of the list
// Add node to the head of the linked list
front->prev = node;
node->next = front;
front = node; // Update head node
// Rear enqueue operation
// Rear of the queue enqueue operation
} else {
// Add node to the tail of the list
// Add node to the tail of the linked list
rear->next = node;
node->prev = rear;
rear = node; // Update tail node
@@ -69,12 +69,12 @@ class LinkedListDeque {
queSize++; // Update queue length
}
/* Front enqueue */
/* Front of the queue enqueue */
void pushFirst(int num) {
push(num, true);
}
/* Rear enqueue */
/* Rear of the queue enqueue */
void pushLast(int num) {
push(num, false);
}
@@ -84,10 +84,10 @@ class LinkedListDeque {
if (isEmpty())
throw out_of_range("Queue is empty");
int val;
// Front dequeue operation
// Temporarily store head node value
if (isFront) {
val = front->val; // Temporarily store the head node value
// Remove head node
val = front->val; // Delete head node
// Delete head node
DoublyListNode *fNext = front->next;
if (fNext != nullptr) {
fNext->prev = nullptr;
@@ -95,10 +95,10 @@ class LinkedListDeque {
}
delete front;
front = fNext; // Update head node
// Rear dequeue operation
// Temporarily store tail node value
} else {
val = rear->val; // Temporarily store the tail node value
// Remove tail node
val = rear->val; // Delete tail node
// Update tail node
DoublyListNode *rPrev = rear->prev;
if (rPrev != nullptr) {
rPrev->next = nullptr;
@@ -111,27 +111,27 @@ class LinkedListDeque {
return val;
}
/* Front dequeue */
/* Rear of the queue dequeue */
int popFirst() {
return pop(true);
}
/* Rear dequeue */
/* Access rear of the queue element */
int popLast() {
return pop(false);
}
/* Access front element */
/* Return list for printing */
int peekFirst() {
if (isEmpty())
throw out_of_range("Double-ended queue is empty");
throw out_of_range("Deque is empty");
return front->val;
}
/* Access rear element */
/* Driver Code */
int peekLast() {
if (isEmpty())
throw out_of_range("Double-ended queue is empty");
throw out_of_range("Deque is empty");
return rear->val;
}
@@ -149,7 +149,7 @@ class LinkedListDeque {
/* Driver Code */
int main() {
/* Initialize double-ended queue */
/* Get the length of the double-ended queue */
LinkedListDeque *deque = new LinkedListDeque();
deque->pushLast(3);
deque->pushLast(2);
@@ -157,35 +157,35 @@ int main() {
cout << "Double-ended queue deque = ";
printVector(deque->toVector());
/* Access element */
/* Update element */
int peekFirst = deque->peekFirst();
cout << "Front element peekFirst = " << peekFirst << endl;
int peekLast = deque->peekLast();
cout << "Back element peekLast = " << peekLast << endl;
cout << "Rear element peekLast = " << peekLast << endl;
/* Element enqueue */
/* Elements enqueue */
deque->pushLast(4);
cout << "Element 4 rear enqueued, deque =";
cout << "After element 4 enqueues at back, deque =";
printVector(deque->toVector());
deque->pushFirst(1);
cout << "Element 1 enqueued at the head, deque = ";
cout << "After element 1 enqueues at front, deque = ";
printVector(deque->toVector());
/* Element dequeue */
int popLast = deque->popLast();
cout << "Deque tail element = " << popLast << ", after dequeuing from the tail";
cout << "Rear dequeue element = " << popLast << ", after rear dequeue, deque = ";
printVector(deque->toVector());
int popFirst = deque->popFirst();
cout << "Deque front element = " << popFirst << ", after dequeuing from the front";
cout << "Front dequeue element = " << popFirst << ", after front dequeue, deque = ";
printVector(deque->toVector());
/* Get the length of the double-ended queue */
int size = deque->size();
cout << "Length of the double-ended queue size = " << size << endl;
cout << "Double-ended queue length size = " << size << endl;
/* Determine if the double-ended queue is empty */
/* Check if the double-ended queue is empty */
bool isEmpty = deque->isEmpty();
cout << "Is the double-ended queue empty = " << boolalpha << isEmpty << endl;
cout << "Double-ended queue is empty = " << boolalpha << isEmpty << endl;
// Free memory
delete deque;
@@ -6,10 +6,10 @@
#include "../utils/common.hpp"
/* Queue class based on linked list */
/* Queue based on linked list implementation */
class LinkedListQueue {
private:
ListNode *front, *rear; // Front node front, back node rear
ListNode *front, *rear; // Head node front, tail node rear
int queSize;
public:
@@ -20,7 +20,7 @@ class LinkedListQueue {
}
~LinkedListQueue() {
// Traverse the linked list, remove nodes, free memory
// Traverse linked list to delete nodes and free memory
freeMemoryLinkedList(front);
}
@@ -29,21 +29,21 @@ class LinkedListQueue {
return queSize;
}
/* Determine if the queue is empty */
/* Check if the queue is empty */
bool isEmpty() {
return queSize == 0;
}
/* Enqueue */
void push(int num) {
// Add num behind the tail node
// Add num after the tail node
ListNode *node = new ListNode(num);
// If the queue is empty, make the head and tail nodes both point to that node
// If the queue is empty, make both front and rear point to the node
if (front == nullptr) {
front = node;
rear = node;
}
// If the queue is not empty, add that node behind the tail node
// If the queue is not empty, add the node after the tail node
else {
rear->next = node;
rear = node;
@@ -54,7 +54,7 @@ class LinkedListQueue {
/* Dequeue */
int pop() {
int num = peek();
// Remove head node
// Delete head node
ListNode *tmp = front;
front = front->next;
// Free memory
@@ -63,14 +63,14 @@ class LinkedListQueue {
return num;
}
/* Access front element */
/* Return list for printing */
int peek() {
if (size() == 0)
throw out_of_range("Queue is empty");
return front->val;
}
/* Convert the linked list to Vector and return */
/* Convert linked list to Vector and return */
vector<int> toVector() {
ListNode *node = front;
vector<int> res(size());
@@ -84,10 +84,10 @@ class LinkedListQueue {
/* Driver Code */
int main() {
/* Initialize queue */
/* Access front of the queue element */
LinkedListQueue *queue = new LinkedListQueue();
/* Element enqueue */
/* Elements enqueue */
queue->push(1);
queue->push(3);
queue->push(2);
@@ -96,22 +96,22 @@ int main() {
cout << "Queue queue = ";
printVector(queue->toVector());
/* Access front element */
/* Return list for printing */
int peek = queue->peek();
cout << "Front element peek = " << peek << endl;
/* Element dequeue */
peek = queue->pop();
cout << "Element dequeued = " << peek << ", after dequeuing";
cout << "Dequeue element pop = " << peek << ", after dequeue, queue = ";
printVector(queue->toVector());
/* Get the length of the queue */
int size = queue->size();
cout << "Length of the queue size = " << size << endl;
cout << "Queue length size = " << size << endl;
/* Determine if the queue is empty */
/* Check if the queue is empty */
bool empty = queue->isEmpty();
cout << "Is the queue empty = " << empty << endl;
cout << "Queue is empty = " << empty << endl;
// Free memory
delete queue;
@@ -6,11 +6,11 @@
#include "../utils/common.hpp"
/* Stack class based on linked list */
/* Stack based on linked list implementation */
class LinkedListStack {
private:
ListNode *stackTop; // Use the head node as the top of the stack
int stkSize; // Length of the stack
ListNode *stackTop; // Use head node as stack top
int stkSize; // Stack length
public:
LinkedListStack() {
@@ -19,7 +19,7 @@ class LinkedListStack {
}
~LinkedListStack() {
// Traverse the linked list, remove nodes, free memory
// Traverse linked list to delete nodes and free memory
freeMemoryLinkedList(stackTop);
}
@@ -28,7 +28,7 @@ class LinkedListStack {
return stkSize;
}
/* Determine if the stack is empty */
/* Check if the stack is empty */
bool isEmpty() {
return size() == 0;
}
@@ -52,14 +52,14 @@ class LinkedListStack {
return num;
}
/* Access stack top element */
/* Return list for printing */
int top() {
if (isEmpty())
throw out_of_range("Stack is empty");
return stackTop->val;
}
/* Convert the List to Array and return */
/* Convert List to Array and return */
vector<int> toVector() {
ListNode *node = stackTop;
vector<int> res(size());
@@ -73,10 +73,10 @@ class LinkedListStack {
/* Driver Code */
int main() {
/* Initialize stack */
/* Access top of the stack element */
LinkedListStack *stack = new LinkedListStack();
/* Element push */
/* Elements push onto stack */
stack->push(1);
stack->push(3);
stack->push(2);
@@ -85,22 +85,22 @@ int main() {
cout << "Stack stack = ";
printVector(stack->toVector());
/* Access stack top element */
/* Return list for printing */
int top = stack->top();
cout << "Top element of the stack top = " << top << endl;
cout << "Stack top element top = " << top << endl;
/* Element pop */
/* Element pop from stack */
top = stack->pop();
cout << "Element popped from the stack = " << top << ", after popping";
cout << "Pop element pop = " << top << ", after pop, stack = ";
printVector(stack->toVector());
/* Get the length of the stack */
int size = stack->size();
cout << "Length of the stack size = " << size << endl;
cout << "Stack length size = " << size << endl;
/* Determine if it's empty */
/* Check if empty */
bool empty = stack->isEmpty();
cout << "Is the stack empty = " << empty << endl;
cout << "Stack is empty = " << empty << endl;
// Free memory
delete stack;
@@ -8,10 +8,10 @@
/* Driver Code */
int main() {
/* Initialize queue */
/* Access front of the queue element */
queue<int> queue;
/* Element enqueue */
/* Elements enqueue */
queue.push(1);
queue.push(3);
queue.push(2);
@@ -20,22 +20,22 @@ int main() {
cout << "Queue queue = ";
printQueue(queue);
/* Access front element */
/* Return list for printing */
int front = queue.front();
cout << "Front element of the queue front = " << front << endl;
cout << "Front element front = " << front << endl;
/* Element dequeue */
queue.pop();
cout << "Element dequeued = " << front << ", after dequeuing";
cout << "Dequeue element front = " << front << ", after dequeue, queue = ";
printQueue(queue);
/* Get the length of the queue */
int size = queue.size();
cout << "Length of the queue size = " << size << endl;
cout << "Queue length size = " << size << endl;
/* Determine if the queue is empty */
/* Check if the queue is empty */
bool empty = queue.empty();
cout << "Is the queue empty = " << empty << endl;
cout << "Queue is empty = " << empty << endl;
return 0;
}
@@ -8,10 +8,10 @@
/* Driver Code */
int main() {
/* Initialize stack */
/* Access top of the stack element */
stack<int> stack;
/* Element push */
/* Elements push onto stack */
stack.push(1);
stack.push(3);
stack.push(2);
@@ -20,22 +20,22 @@ int main() {
cout << "Stack stack = ";
printStack(stack);
/* Access stack top element */
/* Return list for printing */
int top = stack.top();
cout << "Top element of the stack top = " << top << endl;
cout << "Stack top element top = " << top << endl;
/* Element pop */
/* Element pop from stack */
stack.pop(); // No return value
cout << "Element popped from the stack = " << top << ", after popping";
cout << "Pop element pop = " << top << ", after pop, stack = ";
printStack(stack);
/* Get the length of the stack */
int size = stack.size();
cout << "Length of the stack size = " << size << endl;
cout << "Stack length size = " << size << endl;
/* Determine if it's empty */
/* Check if empty */
bool empty = stack.empty();
cout << "Is the stack empty = " << empty << endl;
cout << "Stack is empty = " << empty << endl;
return 0;
}
+26 -26
View File
@@ -6,7 +6,7 @@
#include "../utils/common.hpp"
/* Array-based binary tree class */
/* Binary tree class represented by array */
class ArrayBinaryTree {
public:
/* Constructor */
@@ -19,25 +19,25 @@ class ArrayBinaryTree {
return tree.size();
}
/* Get the value of the node at index i */
/* Get value of node at index i */
int val(int i) {
// If index is out of bounds, return INT_MAX, representing a null
// Return INT_MAX if index out of bounds, representing empty position
if (i < 0 || i >= size())
return INT_MAX;
return tree[i];
}
/* Get the index of the left child of the node at index i */
/* Get index of left child node of node at index i */
int left(int i) {
return 2 * i + 1;
}
/* Get the index of the right child of the node at index i */
/* Get index of right child node of node at index i */
int right(int i) {
return 2 * i + 2;
}
/* Get the index of the parent of the node at index i */
/* Get index of parent node of node at index i */
int parent(int i) {
return (i - 1) / 2;
}
@@ -45,7 +45,7 @@ class ArrayBinaryTree {
/* Level-order traversal */
vector<int> levelOrder() {
vector<int> res;
// Traverse array
// Traverse array directly
for (int i = 0; i < size(); i++) {
if (val(i) != INT_MAX)
res.push_back(val(i));
@@ -53,21 +53,21 @@ class ArrayBinaryTree {
return res;
}
/* Pre-order traversal */
/* Preorder traversal */
vector<int> preOrder() {
vector<int> res;
dfs(0, "pre", res);
return res;
}
/* In-order traversal */
/* Inorder traversal */
vector<int> inOrder() {
vector<int> res;
dfs(0, "in", res);
return res;
}
/* Post-order traversal */
/* Postorder traversal */
vector<int> postOrder() {
vector<int> res;
dfs(0, "post", res);
@@ -79,18 +79,18 @@ class ArrayBinaryTree {
/* Depth-first traversal */
void dfs(int i, string order, vector<int> &res) {
// If it is an empty spot, return
// If empty position, return
if (val(i) == INT_MAX)
return;
// Pre-order traversal
// Preorder traversal
if (order == "pre")
res.push_back(val(i));
dfs(left(i), order, res);
// In-order traversal
// Inorder traversal
if (order == "in")
res.push_back(val(i));
dfs(right(i), order, res);
// Post-order traversal
// Postorder traversal
if (order == "post")
res.push_back(val(i));
}
@@ -99,38 +99,38 @@ class ArrayBinaryTree {
/* Driver Code */
int main() {
// Initialize binary tree
// Use INT_MAX to represent an empty spot nullptr
// Use INT_MAX to represent empty position nullptr
vector<int> arr = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15};
TreeNode *root = vectorToTree(arr);
cout << "\nInitialize binary tree\n";
cout << "Binary tree in array representation:\n";
cout << "Array representation of binary tree:\n";
printVector(arr);
cout << "Binary tree in linked list representation:\n";
cout << "Linked list representation of binary tree:\n";
printTree(root);
// Array-based binary tree class
// Binary tree class represented by array
ArrayBinaryTree abt(arr);
// Access node
int i = 1;
int l = abt.left(i), r = abt.right(i), p = abt.parent(i);
cout << "\nCurrent node's index is " << i << ", value = " << abt.val(i) << "\n";
cout << "Its left child's index is " << l << ", value = " << (l != INT_MAX ? to_string(abt.val(l)) : "nullptr") << "\n";
cout << "Its right child's index is " << r << ", value = " << (r != INT_MAX ? to_string(abt.val(r)) : "nullptr") << "\n";
cout << "Its parent's index is " << p << ", value = " << (p != INT_MAX ? to_string(abt.val(p)) : "nullptr") << "\n";
cout << "\nCurrent node index is " << i << ", value is " << abt.val(i) << "\n";
cout << "Its left child node index is " << l << ", value is " << (abt.val(l) != INT_MAX ? to_string(abt.val(l)) : "nullptr") << "\n";
cout << "Its right child node index is " << r << ", value is " << (abt.val(r) != INT_MAX ? to_string(abt.val(r)) : "nullptr") << "\n";
cout << "Its parent node index is " << p << ", value is " << (abt.val(p) != INT_MAX ? to_string(abt.val(p)) : "nullptr") << "\n";
// Traverse tree
vector<int> res = abt.levelOrder();
cout << "\nLevel-order traversal is:";
cout << "\nLevel-order traversal: ";
printVector(res);
res = abt.preOrder();
cout << "Pre-order traversal is:";
cout << "Pre-order traversal: ";
printVector(res);
res = abt.inOrder();
cout << "In-order traversal is:";
cout << "In-order traversal: ";
printVector(res);
res = abt.postOrder();
cout << "Post-order traversal is:";
cout << "Post-order traversal: ";
printVector(res);
return 0;
+27 -27
View File
@@ -19,13 +19,13 @@ class AVLTree {
TreeNode *rightRotate(TreeNode *node) {
TreeNode *child = node->left;
TreeNode *grandChild = child->right;
// Rotate node to the right around child
// Using child as pivot, rotate node to the right
child->right = node;
node->left = grandChild;
// Update node height
updateHeight(node);
updateHeight(child);
// Return the root of the subtree after rotation
// Return root node of subtree after rotation
return child;
}
@@ -33,19 +33,19 @@ class AVLTree {
TreeNode *leftRotate(TreeNode *node) {
TreeNode *child = node->right;
TreeNode *grandChild = child->left;
// Rotate node to the left around child
// Using child as pivot, rotate node to the left
child->left = node;
node->right = grandChild;
// Update node height
updateHeight(node);
updateHeight(child);
// Return the root of the subtree after rotation
// Return root node of subtree after rotation
return child;
}
/* Perform rotation operation to restore balance to the subtree */
/* Perform rotation operation to restore balance to this subtree */
TreeNode *rotate(TreeNode *node) {
// Get the balance factor of node
// Get balance factor of node
int _balanceFactor = balanceFactor(node);
// Left-leaning tree
if (_balanceFactor > 1) {
@@ -69,7 +69,7 @@ class AVLTree {
return leftRotate(node);
}
}
// Balanced tree, no rotation needed, return
// Balanced tree, no rotation needed, return directly
return node;
}
@@ -83,19 +83,19 @@ class AVLTree {
else if (val > node->val)
node->right = insertHelper(node->right, val);
else
return node; // Do not insert duplicate nodes, return
return node; // Duplicate node not inserted, return directly
updateHeight(node); // Update node height
/* 2. Perform rotation operation to restore balance to the subtree */
/* 2. Perform rotation operation to restore balance to this subtree */
node = rotate(node);
// Return the root node of the subtree
// Return root node of subtree
return node;
}
/* Recursively remove node (helper method) */
/* Recursively delete node (helper method) */
TreeNode *removeHelper(TreeNode *node, int val) {
if (node == nullptr)
return nullptr;
/* 1. Find and remove the node */
/* 1. Find node and delete */
if (val < node->val)
node->left = removeHelper(node->left, val);
else if (val > node->val)
@@ -103,18 +103,18 @@ class AVLTree {
else {
if (node->left == nullptr || node->right == nullptr) {
TreeNode *child = node->left != nullptr ? node->left : node->right;
// Number of child nodes = 0, remove node and return
// Number of child nodes = 0, delete node directly and return
if (child == nullptr) {
delete node;
return nullptr;
}
// Number of child nodes = 1, remove node
// Number of child nodes = 1, delete node directly
else {
delete node;
node = child;
}
} else {
// Number of child nodes = 2, remove the next node in in-order traversal and replace the current node with it
// Number of child nodes = 2, delete the next node in inorder traversal and replace current node with it
TreeNode *temp = node->right;
while (temp->left != nullptr) {
temp = temp->left;
@@ -125,9 +125,9 @@ class AVLTree {
}
}
updateHeight(node); // Update node height
/* 2. Perform rotation operation to restore balance to the subtree */
/* 2. Perform rotation operation to restore balance to this subtree */
node = rotate(node);
// Return the root node of the subtree
// Return root node of subtree
return node;
}
@@ -162,7 +162,7 @@ class AVLTree {
/* Search node */
TreeNode *search(int val) {
TreeNode *cur = root;
// Loop find, break after passing leaf nodes
// Loop search, exit after passing leaf node
while (cur != nullptr) {
// Target node is in cur's right subtree
if (cur->val < val)
@@ -170,7 +170,7 @@ class AVLTree {
// Target node is in cur's left subtree
else if (cur->val > val)
cur = cur->left;
// Found target node, break loop
// Found target node, exit loop
else
break;
}
@@ -190,23 +190,23 @@ class AVLTree {
void testInsert(AVLTree &tree, int val) {
tree.insert(val);
cout << "\nAfter inserting node " << val << ", the AVL tree is" << endl;
cout << "\nAfter inserting node " << val << ", AVL tree is" << endl;
printTree(tree.root);
}
void testRemove(AVLTree &tree, int val) {
tree.remove(val);
cout << "\nAfter removing node " << val << ", the AVL tree is" << endl;
cout << "\nAfter removing node " << val << ", AVL tree is" << endl;
printTree(tree.root);
}
/* Driver Code */
int main() {
/* Initialize empty AVL tree */
/* Please pay attention to how the AVL tree maintains balance after inserting nodes */
AVLTree avlTree;
/* Insert node */
// Notice how the AVL tree maintains balance after inserting nodes
// Delete nodes
testInsert(avlTree, 1);
testInsert(avlTree, 2);
testInsert(avlTree, 3);
@@ -218,16 +218,16 @@ int main() {
testInsert(avlTree, 10);
testInsert(avlTree, 6);
/* Insert duplicate node */
/* Please pay attention to how the AVL tree maintains balance after deleting nodes */
testInsert(avlTree, 7);
/* Remove node */
// Notice how the AVL tree maintains balance after removing nodes
testRemove(avlTree, 8); // Remove node with degree 0
// Delete node with degree 1
testRemove(avlTree, 8); // Delete node with degree 2
testRemove(avlTree, 5); // Remove node with degree 1
testRemove(avlTree, 4); // Remove node with degree 2
/* Search node */
TreeNode *node = avlTree.search(7);
cout << "\nThe found node object is " << node << ", node value =" << node->val << endl;
cout << "\nFound node object is " << node << ", node value = " << node->val << endl;
}
@@ -31,7 +31,7 @@ class BinarySearchTree {
/* Search node */
TreeNode *search(int num) {
TreeNode *cur = root;
// Loop find, break after passing leaf nodes
// Loop search, exit after passing leaf node
while (cur != nullptr) {
// Target node is in cur's right subtree
if (cur->val < num)
@@ -39,7 +39,7 @@ class BinarySearchTree {
// Target node is in cur's left subtree
else if (cur->val > num)
cur = cur->left;
// Found target node, break loop
// Found target node, exit loop
else
break;
}
@@ -55,9 +55,9 @@ class BinarySearchTree {
return;
}
TreeNode *cur = root, *pre = nullptr;
// Loop find, break after passing leaf nodes
// Loop search, exit after passing leaf node
while (cur != nullptr) {
// Found duplicate node, thus return
// Found duplicate node, return directly
if (cur->val == num)
return;
pre = cur;
@@ -78,38 +78,38 @@ class BinarySearchTree {
/* Remove node */
void remove(int num) {
// If tree is empty, return
// If tree is empty, return directly
if (root == nullptr)
return;
TreeNode *cur = root, *pre = nullptr;
// Loop find, break after passing leaf nodes
// Loop search, exit after passing leaf node
while (cur != nullptr) {
// Found node to be removed, break loop
// Found node to delete, exit loop
if (cur->val == num)
break;
pre = cur;
// Node to be removed is in cur's right subtree
// Node to delete is in cur's right subtree
if (cur->val < num)
cur = cur->right;
// Node to be removed is in cur's left subtree
// Node to delete is in cur's left subtree
else
cur = cur->left;
}
// If no node to be removed, return
// If no node to delete, return directly
if (cur == nullptr)
return;
// Number of child nodes = 0 or 1
if (cur->left == nullptr || cur->right == nullptr) {
// When the number of child nodes = 0 / 1, child = nullptr / that child node
// When number of child nodes = 0 / 1, child = nullptr / that child node
TreeNode *child = cur->left != nullptr ? cur->left : cur->right;
// Remove node cur
// Delete node cur
if (cur != root) {
if (pre->left == cur)
pre->left = child;
else
pre->right = child;
} else {
// If the removed node is the root, reassign the root
// If deleted node is root node, reassign root node
root = child;
}
// Free memory
@@ -117,13 +117,13 @@ class BinarySearchTree {
}
// Number of child nodes = 2
else {
// Get the next node in in-order traversal of cur
// Get next node of cur in inorder traversal
TreeNode *tmp = cur->right;
while (tmp->left != nullptr) {
tmp = tmp->left;
}
int tmpVal = tmp->val;
// Recursively remove node tmp
// Recursively delete node tmp
remove(tmp->val);
// Replace cur with tmp
cur->val = tmpVal;
@@ -135,32 +135,32 @@ class BinarySearchTree {
int main() {
/* Initialize binary search tree */
BinarySearchTree *bst = new BinarySearchTree();
// Note that different insertion orders can result in various tree structures. This particular sequence creates a perfect binary tree
// Please note that different insertion orders will generate different binary trees, this sequence can generate a perfect binary tree
vector<int> nums = {8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15};
for (int num : nums) {
bst->insert(num);
}
cout << endl << "The initialized binary tree is\n" << endl;
cout << endl << "Initialized binary tree is\n" << endl;
printTree(bst->getRoot());
/* Search node */
TreeNode *node = bst->search(7);
cout << endl << "The found node object is " << node << ", node value =" << node->val << endl;
cout << endl << "Found node object is " << node << ", node value = " << node->val << endl;
/* Insert node */
bst->insert(16);
cout << endl << "After inserting node 16, the binary tree is\n" << endl;
cout << endl << "After inserting node 16, binary tree is\n" << endl;
printTree(bst->getRoot());
/* Remove node */
bst->remove(1);
cout << endl << "After removing node 1, the binary tree is\n" << endl;
cout << endl << "After removing node 1, binary tree is\n" << endl;
printTree(bst->getRoot());
bst->remove(2);
cout << endl << "After removing node 2, the binary tree is\n" << endl;
cout << endl << "After removing node 2, binary tree is\n" << endl;
printTree(bst->getRoot());
bst->remove(4);
cout << endl << "After removing node 4, the binary tree is\n" << endl;
cout << endl << "After removing node 4, binary tree is\n" << endl;
printTree(bst->getRoot());
// Free memory
+4 -4
View File
@@ -9,13 +9,13 @@
/* Driver Code */
int main() {
/* Initialize binary tree */
// Initialize node
// Initialize nodes
TreeNode *n1 = new TreeNode(1);
TreeNode *n2 = new TreeNode(2);
TreeNode *n3 = new TreeNode(3);
TreeNode *n4 = new TreeNode(4);
TreeNode *n5 = new TreeNode(5);
// Construct node references (pointers)
// Build references (pointers) between nodes
n1->left = n2;
n1->right = n3;
n2->left = n4;
@@ -23,9 +23,9 @@ int main() {
cout << endl << "Initialize binary tree\n" << endl;
printTree(n1);
/* Insert and remove nodes */
/* Insert node P between n1 -> n2 */
TreeNode *P = new TreeNode(0);
// Insert node P between n1 -> n2
// Delete node
n1->left = P;
P->left = n2;
cout << endl << "After inserting node P\n" << endl;
@@ -11,16 +11,16 @@ vector<int> levelOrder(TreeNode *root) {
// Initialize queue, add root node
queue<TreeNode *> queue;
queue.push(root);
// Initialize a list to store the traversal sequence
// Initialize a list to save the traversal sequence
vector<int> vec;
while (!queue.empty()) {
TreeNode *node = queue.front();
queue.pop(); // Queue dequeues
queue.pop(); // Dequeue
vec.push_back(node->val); // Save node value
if (node->left != nullptr)
queue.push(node->left); // Left child node enqueues
queue.push(node->left); // Left child node enqueue
if (node->right != nullptr)
queue.push(node->right); // Right child node enqueues
queue.push(node->right); // Right child node enqueue
}
return vec;
}
@@ -28,14 +28,14 @@ vector<int> levelOrder(TreeNode *root) {
/* Driver Code */
int main() {
/* Initialize binary tree */
// Use a specific function to convert an array into a binary tree
// Here we use a function to generate a binary tree directly from an array
TreeNode *root = vectorToTree(vector<int>{1, 2, 3, 4, 5, 6, 7});
cout << endl << "Initialize binary tree\n" << endl;
printTree(root);
/* Level-order traversal */
vector<int> vec = levelOrder(root);
cout << endl << "Sequence of nodes in level-order traversal = ";
cout << endl << "Level-order traversal node print sequence = ";
printVector(vec);
return 0;
+11 -11
View File
@@ -6,10 +6,10 @@
#include "../utils/common.hpp"
// Initialize the list for storing traversal sequences
// Initialize list for storing traversal sequence
vector<int> vec;
/* Pre-order traversal */
/* Preorder traversal */
void preOrder(TreeNode *root) {
if (root == nullptr)
return;
@@ -19,7 +19,7 @@ void preOrder(TreeNode *root) {
preOrder(root->right);
}
/* In-order traversal */
/* Inorder traversal */
void inOrder(TreeNode *root) {
if (root == nullptr)
return;
@@ -29,7 +29,7 @@ void inOrder(TreeNode *root) {
inOrder(root->right);
}
/* Post-order traversal */
/* Postorder traversal */
void postOrder(TreeNode *root) {
if (root == nullptr)
return;
@@ -42,27 +42,27 @@ void postOrder(TreeNode *root) {
/* Driver Code */
int main() {
/* Initialize binary tree */
// Use a specific function to convert an array into a binary tree
// Here we use a function to generate a binary tree directly from an array
TreeNode *root = vectorToTree(vector<int>{1, 2, 3, 4, 5, 6, 7});
cout << endl << "Initialize binary tree\n" << endl;
printTree(root);
/* Pre-order traversal */
/* Preorder traversal */
vec.clear();
preOrder(root);
cout << endl << "Sequence of nodes in pre-order traversal = ";
cout << endl << "Pre-order traversal node print sequence = ";
printVector(vec);
/* In-order traversal */
/* Inorder traversal */
vec.clear();
inOrder(root);
cout << endl << "Sequence of nodes in in-order traversal = ";
cout << endl << "In-order traversal node print sequence = ";
printVector(vec);
/* Post-order traversal */
/* Postorder traversal */
vec.clear();
postOrder(root);
cout << endl << "Sequence of nodes in post-order traversal = ";
cout << endl << "Post-order traversal node print sequence = ";
printVector(vec);
return 0;
+1 -1
View File
@@ -30,7 +30,7 @@ ListNode *vecToLinkedList(vector<int> list) {
return dum->next;
}
/* Free memory allocated to the linked list */
/* Free memory allocated to linked list */
void freeMemoryLinkedList(ListNode *cur) {
// Free memory
ListNode *pre;
+4 -4
View File
@@ -199,7 +199,7 @@ template <typename T> void printDeque(deque<T> deque) {
}
/* Print hash table */
// Define template parameters TKey and TValue to specify the types of key-value pairs
// Define template parameters TKey and TValue to specify key-value pair types
template <typename TKey, typename TValue> void printHashMap(unordered_map<TKey, TValue> map) {
for (auto kv : map) {
cout << kv.first << " -> " << kv.second << '\n';
@@ -216,12 +216,12 @@ template <typename T, typename S, typename C> S &Container(priority_queue<T, S,
return HackedQueue::Container(pq);
}
/* Print heap (Priority queue) */
/* Print heap (priority queue) */
template <typename T, typename S, typename C> void printHeap(priority_queue<T, S, C> &heap) {
vector<T> vec = Container(heap);
cout << "Array representation of the heap:";
cout << "Heap array representation:";
printVector(vec);
cout << "Tree representation of the heap:" << endl;
cout << "Heap tree representation:" << endl;
TreeNode *root = vectorToTree(vec);
printTree(root);
freeMemoryTree(root);
+6 -6
View File
@@ -23,11 +23,11 @@ struct TreeNode {
}
};
// For serialization encoding rules, refer to:
// For the serialization encoding rules, please refer to:
// https://www.hello-algo.com/chapter_tree/array_representation_of_tree/
// Array representation of the binary tree:
// Array representation of binary tree:
// [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15]
// Linked list representation of the binary tree:
// Linked list representation of binary tree:
// /——— 15
// /——— 7
// /——— 3
@@ -39,7 +39,7 @@ struct TreeNode {
// \——— 4
// \——— 8
/* Deserialize a list into a binary tree: Recursively */
/* Deserialize a list into a binary tree: recursion */
TreeNode *vectorToTreeDFS(vector<int> &arr, int i) {
if (i < 0 || i >= arr.size() || arr[i] == INT_MAX) {
return nullptr;
@@ -55,7 +55,7 @@ TreeNode *vectorToTree(vector<int> arr) {
return vectorToTreeDFS(arr, 0);
}
/* Serialize a binary tree into a list: Recursively */
/* Serialize a binary tree into a list: recursion */
void treeToVecorDFS(TreeNode *root, int i, vector<int> &res) {
if (root == nullptr)
return;
@@ -74,7 +74,7 @@ vector<int> treeToVecor(TreeNode *root) {
return res;
}
/* Free memory allocated to the binary tree */
/* Free binary tree memory */
void freeMemoryTree(TreeNode *root) {
if (root == nullptr)
return;
+2 -2
View File
@@ -17,7 +17,7 @@ struct Vertex {
}
};
/* Input a list of values vals, return a list of vertices vets */
/* Input value list vals, return vertex list vets */
vector<Vertex *> valsToVets(vector<int> vals) {
vector<Vertex *> vets;
for (int val : vals) {
@@ -26,7 +26,7 @@ vector<Vertex *> valsToVets(vector<int> vals) {
return vets;
}
/* Input a list of vertices vets, return a list of values vals */
/* Input vertex list vets, return value list vals */
vector<int> vetsToVals(vector<Vertex *> vets) {
vector<int> vals;
for (Vertex *vet : vets) {