mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-20 02:33:02 +08:00
Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
This commit is contained in:
4
en/codes/cpp/.gitignore
vendored
4
en/codes/cpp/.gitignore
vendored
@@ -1,8 +1,8 @@
|
||||
# Ignore all
|
||||
*
|
||||
# Unignore all with extensions
|
||||
# Unignore all files with extensions
|
||||
!*.*
|
||||
# Unignore all dirs
|
||||
# Unignore all directories
|
||||
!*/
|
||||
|
||||
*.dSYM/
|
||||
|
||||
@@ -6,18 +6,18 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Random access to element */
|
||||
/* Access an element at a random index */
|
||||
int randomAccess(int *nums, int size) {
|
||||
// Randomly select a number from interval [0, size)
|
||||
// Choose a random number in [0, size)
|
||||
int randomIndex = rand() % size;
|
||||
// Retrieve and return the random element
|
||||
// Get and return the randomly selected element
|
||||
int randomNum = nums[randomIndex];
|
||||
return randomNum;
|
||||
}
|
||||
|
||||
/* Extend array length */
|
||||
/* Extend the array length */
|
||||
int *extend(int *nums, int size, int enlarge) {
|
||||
// Initialize an array with extended length
|
||||
// Initialize an array with the 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,38 +25,38 @@ int *extend(int *nums, int size, int enlarge) {
|
||||
}
|
||||
// Free memory
|
||||
delete[] nums;
|
||||
// Return the extended new array
|
||||
// Return the new, extended array
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Insert element num at index index in the array */
|
||||
/* Insert element num at index `index` in the array */
|
||||
void insert(int *nums, int size, int num, int index) {
|
||||
// Move all elements at and after index index backward by one position
|
||||
// Shift all elements at and after index `index` one position to the right
|
||||
for (int i = size - 1; i > index; i--) {
|
||||
nums[i] = nums[i - 1];
|
||||
}
|
||||
// Assign num to the element at index index
|
||||
// Assign num to the element at index `index`
|
||||
nums[index] = num;
|
||||
}
|
||||
|
||||
/* Remove the element at index index */
|
||||
/* Remove the element at index `index` */
|
||||
void remove(int *nums, int size, int index) {
|
||||
// Move all elements after index index forward by one position
|
||||
// Shift all elements after index `index` one position to the left
|
||||
for (int i = index; i < size - 1; i++) {
|
||||
nums[i] = nums[i + 1];
|
||||
}
|
||||
}
|
||||
|
||||
/* Traverse array */
|
||||
/* Traverse the array */
|
||||
void traverse(int *nums, int size) {
|
||||
int count = 0;
|
||||
// Traverse array by index
|
||||
// Traverse the array by index
|
||||
for (int i = 0; i < size; i++) {
|
||||
count += nums[i];
|
||||
}
|
||||
}
|
||||
|
||||
/* Find the specified element in the array */
|
||||
/* Find a specified element in the array */
|
||||
int find(int *nums, int size, int target) {
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (nums[i] == target)
|
||||
@@ -65,9 +65,9 @@ int find(int *nums, int size, int target) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Initialize array */
|
||||
/* Initialize the array */
|
||||
int size = 5;
|
||||
int *arr = new int[size];
|
||||
cout << "Array arr = ";
|
||||
@@ -77,33 +77,33 @@ int main() {
|
||||
cout << "Array nums = ";
|
||||
printArray(nums, size);
|
||||
|
||||
/* Insert element */
|
||||
/* Random access */
|
||||
int randomNum = randomAccess(nums, size);
|
||||
cout << "Get random element in nums " << randomNum << endl;
|
||||
cout << "Randomly selected element from nums: " << randomNum << endl;
|
||||
|
||||
/* Traverse array */
|
||||
/* Extend the length */
|
||||
int enlarge = 3;
|
||||
nums = extend(nums, size, enlarge);
|
||||
size += enlarge;
|
||||
cout << "Extend array length to 8, resulting in nums = ";
|
||||
cout << "Extend the array length to 8, giving nums = ";
|
||||
printArray(nums, size);
|
||||
|
||||
/* Insert element */
|
||||
/* Insert an element */
|
||||
insert(nums, size, 6, 3);
|
||||
cout << "Insert number 6 at index 3, resulting in nums = ";
|
||||
cout << "Insert the number 6 at index 3, giving nums = ";
|
||||
printArray(nums, size);
|
||||
|
||||
/* Remove element */
|
||||
/* Remove an element */
|
||||
remove(nums, size, 2);
|
||||
cout << "Remove element at index 2, resulting in nums = ";
|
||||
cout << "Remove the element at index 2, giving nums = ";
|
||||
printArray(nums, size);
|
||||
|
||||
/* Traverse array */
|
||||
/* Traverse the array */
|
||||
traverse(nums, size);
|
||||
|
||||
/* Find element */
|
||||
/* Find an element */
|
||||
int index = find(nums, size, 3);
|
||||
cout << "Find element 3 in nums, get index = " << index << endl;
|
||||
cout << "Find element 3 in nums, giving index = " << index << endl;
|
||||
|
||||
// Free memory
|
||||
delete[] arr;
|
||||
|
||||
@@ -25,7 +25,7 @@ void remove(ListNode *n0) {
|
||||
delete P;
|
||||
}
|
||||
|
||||
/* Access the node at index 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)
|
||||
@@ -47,40 +47,40 @@ int find(ListNode *head, int target) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Initialize linked list */
|
||||
// Initialize each node
|
||||
/* Initialize the linked list */
|
||||
// Initialize the individual nodes
|
||||
ListNode *n0 = new ListNode(1);
|
||||
ListNode *n1 = new ListNode(3);
|
||||
ListNode *n2 = new ListNode(2);
|
||||
ListNode *n3 = new ListNode(5);
|
||||
ListNode *n4 = new ListNode(4);
|
||||
// Build references between nodes
|
||||
// Set up references between the nodes
|
||||
n0->next = n1;
|
||||
n1->next = n2;
|
||||
n2->next = n3;
|
||||
n3->next = n4;
|
||||
cout << "Initialized linked list is" << endl;
|
||||
cout << "The initialized linked list is" << endl;
|
||||
printLinkedList(n0);
|
||||
|
||||
/* Insert node */
|
||||
/* Insert a node */
|
||||
insert(n0, new ListNode(0));
|
||||
cout << "Linked list after inserting node is" << endl;
|
||||
cout << "The linked list after inserting a node is" << endl;
|
||||
printLinkedList(n0);
|
||||
|
||||
/* Remove node */
|
||||
/* Remove a node */
|
||||
remove(n0);
|
||||
cout << "Linked list after removing node is" << endl;
|
||||
cout << "The linked list after removing a node is" << endl;
|
||||
printLinkedList(n0);
|
||||
|
||||
/* Access node */
|
||||
/* Access a node */
|
||||
ListNode *node = access(n0, 3);
|
||||
cout << "Value of node at index 3 in linked list = " << node->val << endl;
|
||||
cout << "Value of the linked list node at index 3 = " << node->val << endl;
|
||||
|
||||
/* Search node */
|
||||
/* Find a node */
|
||||
int index = find(n0, 2);
|
||||
cout << "Index of node with value 2 in linked list = " << index << endl;
|
||||
cout << "Index of the linked list node with value 2 = " << index << endl;
|
||||
|
||||
// Free memory
|
||||
freeMemoryLinkedList(n0);
|
||||
|
||||
@@ -6,28 +6,28 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Initialize list */
|
||||
/* Initialize the list */
|
||||
vector<int> nums = {1, 3, 2, 5, 4};
|
||||
cout << "List nums = ";
|
||||
printVector(nums);
|
||||
|
||||
/* Update element */
|
||||
/* Access an element */
|
||||
int num = nums[1];
|
||||
cout << "Access element at index 1, get num = " << num << endl;
|
||||
cout << "Access the element at index 1, giving num = " << num << endl;
|
||||
|
||||
/* Add elements at the end */
|
||||
/* Update an element */
|
||||
nums[1] = 0;
|
||||
cout << "Update element at index 1 to 0, resulting in nums = ";
|
||||
cout << "Update the element at index 1 to 0, giving nums = ";
|
||||
printVector(nums);
|
||||
|
||||
/* Remove element */
|
||||
/* Clear the list */
|
||||
nums.clear();
|
||||
cout << "After clearing list, nums = ";
|
||||
cout << "After clearing the list, nums = ";
|
||||
printVector(nums);
|
||||
|
||||
/* Direct traversal of list elements */
|
||||
/* Append an element at the end */
|
||||
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);
|
||||
|
||||
/* Sort list */
|
||||
/* Insert an element in the middle */
|
||||
nums.insert(nums.begin() + 3, 6);
|
||||
cout << "Insert number 6 at index 3, resulting in nums = ";
|
||||
cout << "Insert the number 6 at index 3, giving nums = ";
|
||||
printVector(nums);
|
||||
|
||||
/* Remove element */
|
||||
/* Remove an element */
|
||||
nums.erase(nums.begin() + 3);
|
||||
cout << "Remove element at index 3, resulting in nums = ";
|
||||
cout << "Remove the element at index 3, giving nums = ";
|
||||
printVector(nums);
|
||||
|
||||
/* Traverse list by index */
|
||||
/* Traverse the list by index */
|
||||
int count = 0;
|
||||
for (int i = 0; i < nums.size(); i++) {
|
||||
count += nums[i];
|
||||
}
|
||||
/* Directly traverse list elements */
|
||||
/* Iterate directly over the list elements */
|
||||
count = 0;
|
||||
for (int x : nums) {
|
||||
count += x;
|
||||
@@ -60,12 +60,12 @@ int main() {
|
||||
/* Concatenate two lists */
|
||||
vector<int> nums1 = {6, 8, 7, 10, 9};
|
||||
nums.insert(nums.end(), nums1.begin(), nums1.end());
|
||||
cout << "Concatenate list nums1 to nums, resulting in nums = ";
|
||||
cout << "After appending list nums1 to nums, nums = ";
|
||||
printVector(nums);
|
||||
|
||||
/* Sort list */
|
||||
/* Sort the list */
|
||||
sort(nums.begin(), nums.end());
|
||||
cout << "After sorting list, nums = ";
|
||||
cout << "After sorting the list, nums = ";
|
||||
printVector(nums);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -9,10 +9,10 @@
|
||||
/* List class */
|
||||
class MyList {
|
||||
private:
|
||||
int *arr; // Array (stores list elements)
|
||||
int *arr; // Array (stores the list elements)
|
||||
int arrCapacity = 10; // List capacity
|
||||
int arrSize = 0; // List length (current number of elements)
|
||||
int extendRatio = 2; // Multiple by which the list capacity is extended each time
|
||||
int extendRatio = 2; // Factor by which the list capacity grows each time
|
||||
|
||||
public:
|
||||
/* Constructor */
|
||||
@@ -25,34 +25,34 @@ class MyList {
|
||||
delete[] arr;
|
||||
}
|
||||
|
||||
/* Get list length (current number of elements)*/
|
||||
/* Get the list length (current number of elements)*/
|
||||
int size() {
|
||||
return arrSize;
|
||||
}
|
||||
|
||||
/* Get list capacity */
|
||||
/* Get the list capacity */
|
||||
int capacity() {
|
||||
return arrCapacity;
|
||||
}
|
||||
|
||||
/* Update element */
|
||||
/* Access an element */
|
||||
int get(int index) {
|
||||
// If the index is out of bounds, throw an exception, as below
|
||||
// Raise an exception if the index is out of bounds; the same applies below
|
||||
if (index < 0 || index >= size())
|
||||
throw out_of_range("Index out of bounds");
|
||||
return arr[index];
|
||||
}
|
||||
|
||||
/* Add elements at the end */
|
||||
/* Update an element */
|
||||
void set(int index, int num) {
|
||||
if (index < 0 || index >= size())
|
||||
throw out_of_range("Index out of bounds");
|
||||
arr[index] = num;
|
||||
}
|
||||
|
||||
/* Direct traversal of list elements */
|
||||
/* Append an element at the end */
|
||||
void add(int num) {
|
||||
// When the number of elements exceeds capacity, trigger the extension mechanism
|
||||
// Grow the capacity when adding an element would exceed it
|
||||
if (size() == capacity())
|
||||
extendCapacity();
|
||||
arr[size()] = num;
|
||||
@@ -60,14 +60,14 @@ class MyList {
|
||||
arrSize++;
|
||||
}
|
||||
|
||||
/* Sort list */
|
||||
/* Insert an element in the middle */
|
||||
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 extension mechanism
|
||||
// Grow the capacity when adding an element would exceed it
|
||||
if (size() == capacity())
|
||||
extendCapacity();
|
||||
// Move all elements after index index forward by one position
|
||||
// Shift all elements at and after index `index` one position to the right
|
||||
for (int j = size() - 1; j >= index; j--) {
|
||||
arr[j + 1] = arr[j];
|
||||
}
|
||||
@@ -76,12 +76,12 @@ class MyList {
|
||||
arrSize++;
|
||||
}
|
||||
|
||||
/* Remove element */
|
||||
/* Remove an element */
|
||||
int remove(int index) {
|
||||
if (index < 0 || index >= size())
|
||||
throw out_of_range("Index out of bounds");
|
||||
int num = arr[index];
|
||||
// Create a new array with length _extend_ratio times the original array, and copy the original array to the new array
|
||||
// Shift all elements after index `index` one position to the left
|
||||
for (int j = index; j < size() - 1; j++) {
|
||||
arr[j] = arr[j + 1];
|
||||
}
|
||||
@@ -91,9 +91,9 @@ class MyList {
|
||||
return num;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Grow the list capacity */
|
||||
void extendCapacity() {
|
||||
// Create a new array with length extendRatio times the original array
|
||||
// Create a new array with extendRatio times the original array's length
|
||||
int newCapacity = capacity() * extendRatio;
|
||||
int *tmp = arr;
|
||||
arr = new int[newCapacity];
|
||||
@@ -106,9 +106,9 @@ class MyList {
|
||||
arrCapacity = newCapacity;
|
||||
}
|
||||
|
||||
/* Convert list to Vector for printing */
|
||||
/* Convert the list to a vector for printing */
|
||||
vector<int> toVector() {
|
||||
// Elements enqueue
|
||||
// Convert only the list elements within the occupied range
|
||||
vector<int> vec(size());
|
||||
for (int i = 0; i < size(); i++) {
|
||||
vec[i] = arr[i];
|
||||
@@ -117,11 +117,11 @@ class MyList {
|
||||
}
|
||||
};
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Initialize list */
|
||||
/* Initialize the list */
|
||||
MyList *nums = new MyList();
|
||||
/* Direct traversal of list elements */
|
||||
/* Append an element at the end */
|
||||
nums->add(1);
|
||||
nums->add(3);
|
||||
nums->add(2);
|
||||
@@ -130,39 +130,39 @@ int main() {
|
||||
cout << "List nums = ";
|
||||
vector<int> vec = nums->toVector();
|
||||
printVector(vec);
|
||||
cout << "Capacity = " << nums->capacity() << ", length = " << nums->size() << endl;
|
||||
cout << "Capacity = " << nums->capacity() << " , size = " << nums->size() << endl;
|
||||
|
||||
/* Sort list */
|
||||
/* Insert an element in the middle */
|
||||
nums->insert(3, 6);
|
||||
cout << "Insert number 6 at index 3, resulting in nums = ";
|
||||
cout << "Insert the number 6 at index 3, giving nums = ";
|
||||
vec = nums->toVector();
|
||||
printVector(vec);
|
||||
|
||||
/* Remove element */
|
||||
/* Remove an element */
|
||||
nums->remove(3);
|
||||
cout << "Remove element at index 3, resulting in nums = ";
|
||||
cout << "Remove the element at index 3, giving nums = ";
|
||||
vec = nums->toVector();
|
||||
printVector(vec);
|
||||
|
||||
/* Update element */
|
||||
/* Access an element */
|
||||
int num = nums->get(1);
|
||||
cout << "Access element at index 1, get num = " << num << endl;
|
||||
cout << "Access the element at index 1, giving num = " << num << endl;
|
||||
|
||||
/* Add elements at the end */
|
||||
/* Update an element */
|
||||
nums->set(1, 0);
|
||||
cout << "Update element at index 1 to 0, resulting in nums = ";
|
||||
cout << "Update the element at index 1 to 0, giving nums = ";
|
||||
vec = nums->toVector();
|
||||
printVector(vec);
|
||||
|
||||
/* Test capacity expansion mechanism */
|
||||
/* Test capacity growth */
|
||||
for (int i = 0; i < 10; i++) {
|
||||
// At i = 5, the list length will exceed the list capacity, triggering the expansion mechanism
|
||||
// When i = 5, the list length would exceed its capacity, triggering capacity growth
|
||||
nums->add(i);
|
||||
}
|
||||
cout << "List nums after expansion = ";
|
||||
cout << "List after capacity growth, nums = ";
|
||||
vec = nums->toVector();
|
||||
printVector(vec);
|
||||
cout << "Capacity = " << nums->capacity() << ", length = " << nums->size() << endl;
|
||||
cout << "Capacity = " << nums->capacity() << " , size = " << nums->size() << endl;
|
||||
|
||||
// Free memory
|
||||
delete nums;
|
||||
|
||||
@@ -6,40 +6,40 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Backtracking algorithm: N queens */
|
||||
/* Backtracking: n-queens */
|
||||
void backtrack(int row, int n, vector<vector<string>> &state, vector<vector<vector<string>>> &res, vector<bool> &cols,
|
||||
vector<bool> &diags1, vector<bool> &diags2) {
|
||||
// When all rows are placed, record the solution
|
||||
// Record a solution when a queen has been placed in every row
|
||||
if (row == n) {
|
||||
res.push_back(state);
|
||||
return;
|
||||
}
|
||||
// Traverse all columns
|
||||
// Iterate over all columns
|
||||
for (int col = 0; col < n; col++) {
|
||||
// Calculate the main diagonal and anti-diagonal corresponding to this cell
|
||||
// Calculate the main-diagonal and anti-diagonal indices for this square
|
||||
int diag1 = row - col + n - 1;
|
||||
int diag2 = row + col;
|
||||
// Pruning: do not allow queens to exist in the column, main diagonal, and anti-diagonal of this cell
|
||||
// Prune: the square must have no queen in its column, main diagonal, or anti-diagonal
|
||||
if (!cols[col] && !diags1[diag1] && !diags2[diag2]) {
|
||||
// Attempt: place the queen in this cell
|
||||
// Try: place a queen on this square
|
||||
state[row][col] = "Q";
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = true;
|
||||
// Place the next row
|
||||
// Place a queen in the next row
|
||||
backtrack(row + 1, n, state, res, cols, diags1, diags2);
|
||||
// Backtrack: restore this cell to an empty cell
|
||||
// Backtrack: restore this square to empty
|
||||
state[row][col] = "#";
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Solve N queens */
|
||||
/* Solve the n-queens problem */
|
||||
vector<vector<vector<string>>> nQueens(int n) {
|
||||
// Initialize an n*n chessboard, where 'Q' represents a queen and '#' represents an empty cell
|
||||
// Initialize an n*n board, where 'Q' represents a queen and '#' represents an empty square
|
||||
vector<vector<string>> state(n, vector<string>(n, "#"));
|
||||
vector<bool> cols(n, false); // Record whether there is a queen in the column
|
||||
vector<bool> diags1(2 * n - 1, false); // Record whether there is a queen on the main diagonal
|
||||
vector<bool> diags2(2 * n - 1, false); // Record whether there is a queen on the anti-diagonal
|
||||
vector<bool> cols(n, false); // Track whether a column contains a queen
|
||||
vector<bool> diags1(2 * n - 1, false); // Track whether a main diagonal contains a queen
|
||||
vector<bool> diags2(2 * n - 1, false); // Track whether an anti-diagonal contains a queen
|
||||
vector<vector<vector<string>>> res;
|
||||
|
||||
backtrack(0, n, state, res, cols, diags1, diags2);
|
||||
@@ -47,13 +47,13 @@ vector<vector<vector<string>>> nQueens(int n) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int n = 4;
|
||||
vector<vector<vector<string>>> res = nQueens(n);
|
||||
|
||||
cout << "Input board size is " << n << endl;
|
||||
cout << "Total queen placement solutions: " << res.size() << endl;
|
||||
cout << "Board width and height: " << n << endl;
|
||||
cout << "Queen placements: " << res.size() << " solutions" << endl;
|
||||
for (const vector<vector<string>> &state : res) {
|
||||
cout << "--------------------" << endl;
|
||||
for (const vector<string> &row : state) {
|
||||
|
||||
@@ -6,24 +6,24 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Backtracking algorithm: Permutations I */
|
||||
/* Backtracking: permutations I */
|
||||
void backtrack(vector<int> &state, const vector<int> &choices, vector<bool> &selected, vector<vector<int>> &res) {
|
||||
// When the state length equals the number of elements, record the solution
|
||||
// Record a solution when the state length equals the number of elements
|
||||
if (state.size() == choices.size()) {
|
||||
res.push_back(state);
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
// Iterate over all choices
|
||||
for (int i = 0; i < choices.size(); i++) {
|
||||
int choice = choices[i];
|
||||
// Pruning: do not allow repeated selection of elements
|
||||
// Prune: do not choose an element more than once
|
||||
if (!selected[i]) {
|
||||
// Attempt: make choice, update state
|
||||
// Try: make a choice and update the state
|
||||
selected[i] = true;
|
||||
state.push_back(choice);
|
||||
// Proceed to the next round of selection
|
||||
// Proceed to the next choice
|
||||
backtrack(state, choices, selected, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
selected[i] = false;
|
||||
state.pop_back();
|
||||
}
|
||||
@@ -39,7 +39,7 @@ vector<vector<int>> permutationsI(vector<int> nums) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
vector<int> nums = {1, 2, 3};
|
||||
|
||||
|
||||
@@ -6,26 +6,26 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Backtracking algorithm: Permutations II */
|
||||
/* Backtracking: permutations II */
|
||||
void backtrack(vector<int> &state, const vector<int> &choices, vector<bool> &selected, vector<vector<int>> &res) {
|
||||
// When the state length equals the number of elements, record the solution
|
||||
// Record a solution when the state length equals the number of elements
|
||||
if (state.size() == choices.size()) {
|
||||
res.push_back(state);
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
// Iterate over all choices
|
||||
unordered_set<int> duplicated;
|
||||
for (int i = 0; i < choices.size(); i++) {
|
||||
int choice = choices[i];
|
||||
// Pruning: do not allow repeated selection of elements and do not allow repeated selection of equal elements
|
||||
// Prune: do not reuse an element or choose the same value again at this depth
|
||||
if (!selected[i] && duplicated.find(choice) == duplicated.end()) {
|
||||
// Attempt: make choice, update state
|
||||
duplicated.emplace(choice); // Record the selected element value
|
||||
// Try: make a choice and update the state
|
||||
duplicated.emplace(choice); // Record the chosen value
|
||||
selected[i] = true;
|
||||
state.push_back(choice);
|
||||
// Proceed to the next round of selection
|
||||
// Proceed to the next choice
|
||||
backtrack(state, choices, selected, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
selected[i] = false;
|
||||
state.pop_back();
|
||||
}
|
||||
@@ -41,7 +41,7 @@ vector<vector<int>> permutationsII(vector<int> nums) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
vector<int> nums = {1, 1, 2};
|
||||
|
||||
|
||||
@@ -8,23 +8,23 @@
|
||||
|
||||
vector<TreeNode *> res;
|
||||
|
||||
/* Preorder traversal: Example 1 */
|
||||
/* Preorder traversal: example 1 */
|
||||
void preOrder(TreeNode *root) {
|
||||
if (root == nullptr) {
|
||||
return;
|
||||
}
|
||||
if (root->val == 7) {
|
||||
// Record solution
|
||||
// Record the solution
|
||||
res.push_back(root);
|
||||
}
|
||||
preOrder(root->left);
|
||||
preOrder(root->right);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
TreeNode *root = vectorToTree(vector<int>{1, 7, 3, 4, 5, 6, 7});
|
||||
cout << "\nInitialize binary tree" << endl;
|
||||
cout << "\nInitialize the binary tree" << endl;
|
||||
printTree(root);
|
||||
|
||||
// Preorder traversal
|
||||
|
||||
@@ -9,15 +9,15 @@
|
||||
vector<TreeNode *> path;
|
||||
vector<vector<TreeNode *>> res;
|
||||
|
||||
/* Preorder traversal: Example 2 */
|
||||
/* Preorder traversal: example 2 */
|
||||
void preOrder(TreeNode *root) {
|
||||
if (root == nullptr) {
|
||||
return;
|
||||
}
|
||||
// Attempt
|
||||
// Try
|
||||
path.push_back(root);
|
||||
if (root->val == 7) {
|
||||
// Record solution
|
||||
// Record the solution
|
||||
res.push_back(path);
|
||||
}
|
||||
preOrder(root->left);
|
||||
@@ -26,16 +26,16 @@ void preOrder(TreeNode *root) {
|
||||
path.pop_back();
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
TreeNode *root = vectorToTree(vector<int>{1, 7, 3, 4, 5, 6, 7});
|
||||
cout << "\nInitialize binary tree" << endl;
|
||||
cout << "\nInitialize the binary tree" << endl;
|
||||
printTree(root);
|
||||
|
||||
// Preorder traversal
|
||||
preOrder(root);
|
||||
|
||||
cout << "\nOutput all paths from root node to node 7" << endl;
|
||||
cout << "\nOutput all paths from the root to nodes with value 7" << endl;
|
||||
for (vector<TreeNode *> &path : res) {
|
||||
vector<int> vals;
|
||||
for (TreeNode *node : path) {
|
||||
|
||||
@@ -9,16 +9,16 @@
|
||||
vector<TreeNode *> path;
|
||||
vector<vector<TreeNode *>> res;
|
||||
|
||||
/* Preorder traversal: Example 3 */
|
||||
/* Preorder traversal: example 3 */
|
||||
void preOrder(TreeNode *root) {
|
||||
// Pruning
|
||||
// Prune
|
||||
if (root == nullptr || root->val == 3) {
|
||||
return;
|
||||
}
|
||||
// Attempt
|
||||
// Try
|
||||
path.push_back(root);
|
||||
if (root->val == 7) {
|
||||
// Record solution
|
||||
// Record the solution
|
||||
res.push_back(path);
|
||||
}
|
||||
preOrder(root->left);
|
||||
@@ -27,16 +27,16 @@ void preOrder(TreeNode *root) {
|
||||
path.pop_back();
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
TreeNode *root = vectorToTree(vector<int>{1, 7, 3, 4, 5, 6, 7});
|
||||
cout << "\nInitialize binary tree" << endl;
|
||||
cout << "\nInitialize the binary tree" << endl;
|
||||
printTree(root);
|
||||
|
||||
// Preorder traversal
|
||||
preOrder(root);
|
||||
|
||||
cout << "\nOutput all paths from root node to node 7, requiring paths do not include nodes with value 3" << endl;
|
||||
cout << "\nOutput all paths from the root to nodes with value 7, requiring that no node on the path has value 3" << endl;
|
||||
for (vector<TreeNode *> &path : res) {
|
||||
vector<int> vals;
|
||||
for (TreeNode *node : path) {
|
||||
|
||||
@@ -6,57 +6,57 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Check if the current state is a solution */
|
||||
/* Check whether the current state is a solution */
|
||||
bool isSolution(vector<TreeNode *> &state) {
|
||||
return !state.empty() && state.back()->val == 7;
|
||||
}
|
||||
|
||||
/* Record solution */
|
||||
/* Record the solution */
|
||||
void recordSolution(vector<TreeNode *> &state, vector<vector<TreeNode *>> &res) {
|
||||
res.push_back(state);
|
||||
}
|
||||
|
||||
/* Check if the choice is valid under the current state */
|
||||
/* Check whether the choice is valid in the current state */
|
||||
bool isValid(vector<TreeNode *> &state, TreeNode *choice) {
|
||||
return choice != nullptr && choice->val != 3;
|
||||
}
|
||||
|
||||
/* Update state */
|
||||
/* Update the state */
|
||||
void makeChoice(vector<TreeNode *> &state, TreeNode *choice) {
|
||||
state.push_back(choice);
|
||||
}
|
||||
|
||||
/* Restore state */
|
||||
/* Restore the state */
|
||||
void undoChoice(vector<TreeNode *> &state, TreeNode *choice) {
|
||||
state.pop_back();
|
||||
}
|
||||
|
||||
/* Backtracking algorithm: Example 3 */
|
||||
/* Backtracking: example 3 */
|
||||
void backtrack(vector<TreeNode *> &state, vector<TreeNode *> &choices, vector<vector<TreeNode *>> &res) {
|
||||
// Check if it is a solution
|
||||
// Check whether this is a solution
|
||||
if (isSolution(state)) {
|
||||
// Record solution
|
||||
// Record the solution
|
||||
recordSolution(state, res);
|
||||
}
|
||||
// Traverse all choices
|
||||
// Iterate over all choices
|
||||
for (TreeNode *choice : choices) {
|
||||
// Pruning: check if the choice is valid
|
||||
// Prune: check whether the choice is valid
|
||||
if (isValid(state, choice)) {
|
||||
// Attempt: make choice, update state
|
||||
// Try: make a choice and update the state
|
||||
makeChoice(state, choice);
|
||||
// Proceed to the next round of selection
|
||||
// Proceed to the next choice
|
||||
vector<TreeNode *> nextChoices{choice->left, choice->right};
|
||||
backtrack(state, nextChoices, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
undoChoice(state, choice);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
TreeNode *root = vectorToTree(vector<int>{1, 7, 3, 4, 5, 6, 7});
|
||||
cout << "\nInitialize binary tree" << endl;
|
||||
cout << "\nInitialize the binary tree" << endl;
|
||||
printTree(root);
|
||||
|
||||
// Backtracking algorithm
|
||||
@@ -65,7 +65,7 @@ int main() {
|
||||
vector<vector<TreeNode *>> res;
|
||||
backtrack(state, choices, res);
|
||||
|
||||
cout << "\nOutput all paths from root node to node 7, requiring paths do not include nodes with value 3" << endl;
|
||||
cout << "\nOutput all paths from the root to nodes with value 7, requiring that no node on the path has value 3" << endl;
|
||||
for (vector<TreeNode *> &path : res) {
|
||||
vector<int> vals;
|
||||
for (TreeNode *node : path) {
|
||||
|
||||
@@ -6,26 +6,26 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Backtracking algorithm: Subset sum I */
|
||||
/* Backtracking: subset sum I */
|
||||
void backtrack(vector<int> &state, int target, vector<int> &choices, int start, vector<vector<int>> &res) {
|
||||
// When the subset sum equals target, record the solution
|
||||
// Record a solution when the remaining target reaches 0
|
||||
if (target == 0) {
|
||||
res.push_back(state);
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
// Pruning 2: start traversing from start to avoid generating duplicate subsets
|
||||
// Iterate over all choices
|
||||
// Pruning 2: iterate from start to avoid generating duplicate subsets
|
||||
for (int i = start; i < choices.size(); i++) {
|
||||
// Pruning 1: if the subset sum exceeds target, end the loop directly
|
||||
// This is because the array is sorted, and later elements are larger, so the subset sum will definitely exceed target
|
||||
// Pruning 1: exit the loop if this choice exceeds the remaining target
|
||||
// The array is sorted, so later elements are at least as large and also exceed the remaining target
|
||||
if (target - choices[i] < 0) {
|
||||
break;
|
||||
}
|
||||
// Attempt: make choice, update target, start
|
||||
// Try: make a choice and update target and start
|
||||
state.push_back(choices[i]);
|
||||
// Proceed to the next round of selection
|
||||
// Proceed to the next choice
|
||||
backtrack(state, target - choices[i], choices, i, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
state.pop_back();
|
||||
}
|
||||
}
|
||||
@@ -34,13 +34,13 @@ void backtrack(vector<int> &state, int target, vector<int> &choices, int start,
|
||||
vector<vector<int>> subsetSumI(vector<int> &nums, int target) {
|
||||
vector<int> state; // State (subset)
|
||||
sort(nums.begin(), nums.end()); // Sort nums
|
||||
int start = 0; // Start point for traversal
|
||||
vector<vector<int>> res; // Result list (subset list)
|
||||
int start = 0; // Starting index for iteration
|
||||
vector<vector<int>> res; // Result list (list of subsets)
|
||||
backtrack(state, target, nums, start, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
vector<int> nums = {3, 4, 5};
|
||||
int target = 9;
|
||||
@@ -50,7 +50,7 @@ int main() {
|
||||
cout << "Input array nums = ";
|
||||
printVector(nums);
|
||||
cout << "target = " << target << endl;
|
||||
cout << "All subsets with sum equal to " << target << " are res = " << endl;
|
||||
cout << "All subsets with sum " << target << " , res = " << endl;
|
||||
printVectorMatrix(res);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -6,38 +6,38 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Backtracking algorithm: Subset sum I */
|
||||
/* Backtracking: subset sum I */
|
||||
void backtrack(vector<int> &state, int target, int total, vector<int> &choices, vector<vector<int>> &res) {
|
||||
// When the subset sum equals target, record the solution
|
||||
// Record a solution when the subset sum equals target
|
||||
if (total == target) {
|
||||
res.push_back(state);
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
// Iterate over all choices
|
||||
for (size_t i = 0; i < choices.size(); i++) {
|
||||
// Pruning: if the subset sum exceeds target, skip this choice
|
||||
// Prune: skip this choice if the subset sum would exceed target
|
||||
if (total + choices[i] > target) {
|
||||
continue;
|
||||
}
|
||||
// Attempt: make choice, update element sum total
|
||||
// Try: make a choice and update the sum total
|
||||
state.push_back(choices[i]);
|
||||
// Proceed to the next round of selection
|
||||
// Proceed to the next choice
|
||||
backtrack(state, target, total + choices[i], choices, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
state.pop_back();
|
||||
}
|
||||
}
|
||||
|
||||
/* Solve subset sum I (including duplicate subsets) */
|
||||
/* Solve subset sum I (with duplicate subsets) */
|
||||
vector<vector<int>> subsetSumINaive(vector<int> &nums, int target) {
|
||||
vector<int> state; // State (subset)
|
||||
int total = 0; // Subset sum
|
||||
vector<vector<int>> res; // Result list (subset list)
|
||||
vector<vector<int>> res; // Result list (list of subsets)
|
||||
backtrack(state, target, total, nums, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
vector<int> nums = {3, 4, 5};
|
||||
int target = 9;
|
||||
@@ -47,7 +47,7 @@ int main() {
|
||||
cout << "Input array nums = ";
|
||||
printVector(nums);
|
||||
cout << "target = " << target << endl;
|
||||
cout << "All subsets with sum equal to " << target << " are res = " << endl;
|
||||
cout << "All subsets with sum " << target << " , res = " << endl;
|
||||
printVectorMatrix(res);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -6,31 +6,31 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Backtracking algorithm: Subset sum II */
|
||||
/* Backtracking: subset sum II */
|
||||
void backtrack(vector<int> &state, int target, vector<int> &choices, int start, vector<vector<int>> &res) {
|
||||
// When the subset sum equals target, record the solution
|
||||
// Record a solution when the remaining target reaches 0
|
||||
if (target == 0) {
|
||||
res.push_back(state);
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
// Pruning 2: start traversing from start to avoid generating duplicate subsets
|
||||
// Pruning 3: start traversing from start to avoid repeatedly selecting the same element
|
||||
// Iterate over all choices
|
||||
// Pruning 2: iterate from start to avoid generating duplicate subsets
|
||||
// Pruning 3: iterate from start to avoid choosing the same element again
|
||||
for (int i = start; i < choices.size(); i++) {
|
||||
// Pruning 1: if the subset sum exceeds target, end the loop directly
|
||||
// This is because the array is sorted, and later elements are larger, so the subset sum will definitely exceed target
|
||||
// Pruning 1: exit the loop if this choice exceeds the remaining target
|
||||
// The array is sorted, so later elements are at least as large and also exceed the remaining target
|
||||
if (target - choices[i] < 0) {
|
||||
break;
|
||||
}
|
||||
// Pruning 4: if this element equals the left element, it means this search branch is duplicate, skip it directly
|
||||
// Pruning 4: if this element equals its left neighbor at the same search depth, the branch is a duplicate; skip it
|
||||
if (i > start && choices[i] == choices[i - 1]) {
|
||||
continue;
|
||||
}
|
||||
// Attempt: make choice, update target, start
|
||||
// Try: make a choice and update target and start
|
||||
state.push_back(choices[i]);
|
||||
// Proceed to the next round of selection
|
||||
// Proceed to the next choice
|
||||
backtrack(state, target - choices[i], choices, i + 1, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
state.pop_back();
|
||||
}
|
||||
}
|
||||
@@ -39,13 +39,13 @@ void backtrack(vector<int> &state, int target, vector<int> &choices, int start,
|
||||
vector<vector<int>> subsetSumII(vector<int> &nums, int target) {
|
||||
vector<int> state; // State (subset)
|
||||
sort(nums.begin(), nums.end()); // Sort nums
|
||||
int start = 0; // Start point for traversal
|
||||
vector<vector<int>> res; // Result list (subset list)
|
||||
int start = 0; // Starting index for iteration
|
||||
vector<vector<int>> res; // Result list (list of subsets)
|
||||
backtrack(state, target, nums, start, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
vector<int> nums = {4, 4, 5};
|
||||
int target = 9;
|
||||
@@ -55,7 +55,7 @@ int main() {
|
||||
cout << "Input array nums = ";
|
||||
printVector(nums);
|
||||
cout << "target = " << target << endl;
|
||||
cout << "All subsets with sum equal to " << target << " are res = " << endl;
|
||||
cout << "All subsets with sum " << target << " , res = " << endl;
|
||||
printVectorMatrix(res);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
#include <cassert>
|
||||
|
||||
/* Iterative summation */
|
||||
/* Sum using iteration */
|
||||
int sumIter(int n) {
|
||||
int res = 0;
|
||||
for (int i = 1; i <= n; ++i) {
|
||||
@@ -15,7 +15,7 @@ int sumIter(int n) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Recursive summation */
|
||||
/* Sum using recursion */
|
||||
int sumRecur(int n) {
|
||||
if (n == 1) {
|
||||
return 1;
|
||||
@@ -23,7 +23,7 @@ int sumRecur(int n) {
|
||||
return n + sumRecur(n - 1);
|
||||
}
|
||||
|
||||
/* Linear loop */
|
||||
/* Linear-time loop */
|
||||
int linearLoop(int n) {
|
||||
int res = 0;
|
||||
for (int i = 0; i < n; ++i) {
|
||||
@@ -32,7 +32,7 @@ int linearLoop(int n) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Quadratic loop */
|
||||
/* Quadratic-time loop */
|
||||
int quadraticLoop(int n) {
|
||||
int res = 0;
|
||||
for (int i = 0; i < n; ++i) {
|
||||
@@ -43,7 +43,7 @@ int quadraticLoop(int n) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Logarithmic loop */
|
||||
/* Logarithmic-time loop */
|
||||
int logarithmicLoop(int n) {
|
||||
while (n > 1) {
|
||||
n /= 2;
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
/* for loop */
|
||||
int forLoop(int n) {
|
||||
int res = 0;
|
||||
// Sum 1, 2, ..., n-1, n
|
||||
// Sum 1, 2, ..., n-1, n in a loop
|
||||
for (int i = 1; i <= n; ++i) {
|
||||
res += i;
|
||||
}
|
||||
@@ -19,11 +19,11 @@ int forLoop(int n) {
|
||||
/* while loop */
|
||||
int whileLoop(int n) {
|
||||
int res = 0;
|
||||
int i = 1; // Initialize condition variable
|
||||
// Sum 1, 2, ..., n-1, n
|
||||
int i = 1; // Initialize the loop control variable
|
||||
// Sum 1, 2, ..., n-1, n in a loop
|
||||
while (i <= n) {
|
||||
res += i;
|
||||
i++; // Update condition variable
|
||||
i++; // Update the loop control variable
|
||||
}
|
||||
return res;
|
||||
}
|
||||
@@ -31,23 +31,23 @@ int whileLoop(int n) {
|
||||
/* while loop (two updates) */
|
||||
int whileLoopII(int n) {
|
||||
int res = 0;
|
||||
int i = 1; // Initialize condition variable
|
||||
// Sum 1, 4, 10, ...
|
||||
int i = 1; // Initialize the loop control variable
|
||||
// Sum 1, 4, 10, ... in a loop
|
||||
while (i <= n) {
|
||||
res += i;
|
||||
// Update condition variable
|
||||
// Update the loop control variable
|
||||
i++;
|
||||
i *= 2;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Nested for loop */
|
||||
/* Nested for loops */
|
||||
string nestedForLoop(int n) {
|
||||
ostringstream res;
|
||||
// Loop i = 1, 2, ..., n-1, n
|
||||
// Loop over i = 1, 2, ..., n-1, n
|
||||
for (int i = 1; i <= n; ++i) {
|
||||
// Loop j = 1, 2, ..., n-1, n
|
||||
// Loop over j = 1, 2, ..., n-1, n
|
||||
for (int j = 1; j <= n; ++j) {
|
||||
res << "(" << i << ", " << j << "), ";
|
||||
}
|
||||
@@ -55,22 +55,22 @@ string nestedForLoop(int n) {
|
||||
return res.str();
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int n = 5;
|
||||
int res;
|
||||
|
||||
res = forLoop(n);
|
||||
cout << "\nfor loop sum result res = " << res << endl;
|
||||
cout << "\nSum from the for loop, res = " << res << endl;
|
||||
|
||||
res = whileLoop(n);
|
||||
cout << "\nwhile loop sum result res = " << res << endl;
|
||||
cout << "\nSum from the while loop, res = " << res << endl;
|
||||
|
||||
res = whileLoopII(n);
|
||||
cout << "\nwhile loop (two updates) sum result res = " << res << endl;
|
||||
cout << "\nSum from the while loop with two updates, res = " << res << endl;
|
||||
|
||||
string resStr = nestedForLoop(n);
|
||||
cout << "\nDouble for loop traversal result " << resStr << endl;
|
||||
cout << "\nTraversal result from the nested for loops: " << resStr << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -8,12 +8,12 @@
|
||||
|
||||
/* Recursion */
|
||||
int recur(int n) {
|
||||
// Termination condition
|
||||
// Base case
|
||||
if (n == 1)
|
||||
return 1;
|
||||
// Recurse: recursive call
|
||||
// Recurse: make a recursive call
|
||||
int res = recur(n - 1);
|
||||
// Return: return result
|
||||
// Unwind: return the result
|
||||
return n + res;
|
||||
}
|
||||
|
||||
@@ -22,14 +22,14 @@ int forLoopRecur(int n) {
|
||||
// Use an explicit stack to simulate the system call stack
|
||||
stack<int> stack;
|
||||
int res = 0;
|
||||
// Recurse: recursive call
|
||||
// Recurse: make a recursive call
|
||||
for (int i = n; i > 0; i--) {
|
||||
// Simulate "recurse" with "push"
|
||||
// Simulate recursive calls by pushing onto the stack
|
||||
stack.push(i);
|
||||
}
|
||||
// Return: return result
|
||||
// Unwind: return the result
|
||||
while (!stack.empty()) {
|
||||
// Simulate "return" with "pop"
|
||||
// Simulate unwinding by popping from the stack
|
||||
res += stack.top();
|
||||
stack.pop();
|
||||
}
|
||||
@@ -39,40 +39,40 @@ int forLoopRecur(int n) {
|
||||
|
||||
/* Tail recursion */
|
||||
int tailRecur(int n, int res) {
|
||||
// Termination condition
|
||||
// Base case
|
||||
if (n == 0)
|
||||
return res;
|
||||
// Tail recursive call
|
||||
// Tail-recursive call
|
||||
return tailRecur(n - 1, res + n);
|
||||
}
|
||||
|
||||
/* Fibonacci sequence: recursion */
|
||||
int fib(int n) {
|
||||
// Termination condition f(1) = 0, f(2) = 1
|
||||
// Base cases: f(1) = 0, f(2) = 1
|
||||
if (n == 1 || n == 2)
|
||||
return n - 1;
|
||||
// Recursive call f(n) = f(n-1) + f(n-2)
|
||||
// Recursive calls: f(n) = f(n-1) + f(n-2)
|
||||
int res = fib(n - 1) + fib(n - 2);
|
||||
// Return result f(n)
|
||||
// Return the result f(n)
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int n = 5;
|
||||
int res;
|
||||
|
||||
res = recur(n);
|
||||
cout << "\nRecursive function sum result res = " << res << endl;
|
||||
cout << "\nSum from the recursive function, res = " << res << endl;
|
||||
|
||||
res = forLoopRecur(n);
|
||||
cout << "\nUsing iteration to simulate recursive sum result res = " << res << endl;
|
||||
cout << "\nSum from simulating recursion with iteration, res = " << res << endl;
|
||||
|
||||
res = tailRecur(n, 0);
|
||||
cout << "\nTail recursive function sum result res = " << res << endl;
|
||||
cout << "\nSum from the tail-recursive function, res = " << res << endl;
|
||||
|
||||
res = fib(n);
|
||||
cout << "\nThe " << n << "th term of the Fibonacci sequence is " << res << endl;
|
||||
cout << "\nFibonacci term " << n << " is " << res << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -12,9 +12,9 @@ int func() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Constant order */
|
||||
/* Constant complexity */
|
||||
void constant(int n) {
|
||||
// Constants, variables, objects occupy O(1) space
|
||||
// Constants, variables, and objects occupy O(1) space
|
||||
const int a = 0;
|
||||
int b = 0;
|
||||
vector<int> nums(10000);
|
||||
@@ -23,39 +23,39 @@ void constant(int n) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
int c = 0;
|
||||
}
|
||||
// Functions in the loop occupy O(1) space
|
||||
// Function calls in the loop occupy O(1) space
|
||||
for (int i = 0; i < n; i++) {
|
||||
func();
|
||||
}
|
||||
}
|
||||
|
||||
/* Linear order */
|
||||
/* Linear complexity */
|
||||
void linear(int n) {
|
||||
// Array of length n uses O(n) space
|
||||
// An array of length n uses O(n) space
|
||||
vector<int> nums(n);
|
||||
// A list of length n occupies O(n) space
|
||||
vector<ListNode> nodes;
|
||||
for (int i = 0; i < n; i++) {
|
||||
nodes.push_back(ListNode(i));
|
||||
}
|
||||
// A hash table of length n occupies O(n) space
|
||||
// A hash table with n entries occupies O(n) space
|
||||
unordered_map<int, string> map;
|
||||
for (int i = 0; i < n; i++) {
|
||||
map[i] = to_string(i);
|
||||
}
|
||||
}
|
||||
|
||||
/* Linear order (recursive implementation) */
|
||||
/* Linear complexity (recursive implementation) */
|
||||
void linearRecur(int n) {
|
||||
cout << "Recursion n = " << n << endl;
|
||||
cout << "Recursion: n = " << n << endl;
|
||||
if (n == 1)
|
||||
return;
|
||||
linearRecur(n - 1);
|
||||
}
|
||||
|
||||
/* Exponential order */
|
||||
/* Quadratic complexity */
|
||||
void quadratic(int n) {
|
||||
// 2D list uses O(n^2) space
|
||||
// The two-dimensional list occupies 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 order (recursive implementation) */
|
||||
/* Quadratic complexity (recursive implementation) */
|
||||
int quadraticRecur(int n) {
|
||||
if (n <= 0)
|
||||
return 0;
|
||||
vector<int> nums(n);
|
||||
cout << "In recursion n = " << n << ", nums length = " << nums.size() << endl;
|
||||
cout << "Recursion: n = " << n << " , length of nums = " << nums.size() << endl;
|
||||
return quadraticRecur(n - 1);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Exponential complexity (building a perfect binary tree) */
|
||||
TreeNode *buildTree(int n) {
|
||||
if (n == 0)
|
||||
return nullptr;
|
||||
@@ -85,18 +85,18 @@ TreeNode *buildTree(int n) {
|
||||
return root;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int n = 5;
|
||||
// Constant order
|
||||
// Constant complexity
|
||||
constant(n);
|
||||
// Linear order
|
||||
// Linear complexity
|
||||
linear(n);
|
||||
linearRecur(n);
|
||||
// Exponential order
|
||||
// Quadratic complexity
|
||||
quadratic(n);
|
||||
quadraticRecur(n);
|
||||
// Exponential order
|
||||
// Exponential complexity
|
||||
TreeNode *root = buildTree(n);
|
||||
printTree(root);
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Constant order */
|
||||
/* Constant complexity */
|
||||
int constant(int n) {
|
||||
int count = 0;
|
||||
int size = 100000;
|
||||
@@ -15,7 +15,7 @@ int constant(int n) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Linear order */
|
||||
/* Linear complexity */
|
||||
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 order (traversing array) */
|
||||
/* Linear complexity (array traversal) */
|
||||
int arrayTraversal(vector<int> &nums) {
|
||||
int count = 0;
|
||||
// Number of iterations is proportional to the array length
|
||||
// The number of iterations is proportional to the array length
|
||||
for (int num : nums) {
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Exponential order */
|
||||
/* Quadratic complexity */
|
||||
int quadratic(int n) {
|
||||
int count = 0;
|
||||
// Number of iterations is quadratically related to the data size n
|
||||
// The number of iterations is proportional to the square of the input 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 order (bubble sort) */
|
||||
/* Quadratic complexity (bubble sort) */
|
||||
int bubbleSort(vector<int> &nums) {
|
||||
int count = 0; // Counter
|
||||
// Outer loop: unsorted range is [0, i]
|
||||
// Outer loop: the 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 rightmost end of that range
|
||||
// Inner loop: move the largest element in the unsorted range [0, i] to its right end through swaps
|
||||
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 unit operations
|
||||
count += 3; // Swapping two elements takes 3 elementary operations
|
||||
}
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Exponential order (loop implementation) */
|
||||
/* Exponential complexity (iterative implementation) */
|
||||
int exponential(int n) {
|
||||
int count = 0, base = 1;
|
||||
// Cells divide into two every round, forming sequence 1, 2, 4, 8, ..., 2^(n-1)
|
||||
// Each cell divides into two per round, giving the 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 order (recursive implementation) */
|
||||
/* Exponential complexity (recursive implementation) */
|
||||
int expRecur(int n) {
|
||||
if (n == 1)
|
||||
return 1;
|
||||
return expRecur(n - 1) + expRecur(n - 1) + 1;
|
||||
}
|
||||
|
||||
/* Logarithmic order (loop implementation) */
|
||||
/* Logarithmic complexity (iterative implementation) */
|
||||
int logarithmic(int n) {
|
||||
int count = 0;
|
||||
while (n > 1) {
|
||||
@@ -95,14 +95,14 @@ int logarithmic(int n) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Logarithmic order (recursive implementation) */
|
||||
/* Logarithmic complexity (recursive implementation) */
|
||||
int logRecur(int n) {
|
||||
if (n <= 1)
|
||||
return 0;
|
||||
return logRecur(n / 2) + 1;
|
||||
}
|
||||
|
||||
/* Linearithmic order */
|
||||
/* Linearithmic complexity */
|
||||
int linearLogRecur(int n) {
|
||||
if (n <= 1)
|
||||
return 1;
|
||||
@@ -113,56 +113,56 @@ int linearLogRecur(int n) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Factorial order (recursive implementation) */
|
||||
/* Factorial complexity (recursive implementation) */
|
||||
int factorialRecur(int n) {
|
||||
if (n == 0)
|
||||
return 1;
|
||||
int count = 0;
|
||||
// Split from 1 into n
|
||||
// Split one problem into n subproblems
|
||||
for (int i = 0; i < n; i++) {
|
||||
count += factorialRecur(n - 1);
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
// You can modify n to run and observe the trend of the number of operations for various complexities
|
||||
// Try different values of n to see how the operation count grows for each complexity
|
||||
int n = 8;
|
||||
cout << "Input data size n = " << n << endl;
|
||||
cout << "Input size n = " << n << endl;
|
||||
|
||||
int count = constant(n);
|
||||
cout << "Constant order operation count = " << count << endl;
|
||||
cout << "Operation count for constant complexity = " << count << endl;
|
||||
|
||||
count = linear(n);
|
||||
cout << "Linear order operation count = " << count << endl;
|
||||
cout << "Operation count for linear complexity = " << count << endl;
|
||||
vector<int> arr(n);
|
||||
count = arrayTraversal(arr);
|
||||
cout << "Linear order (array traversal) operation count = " << count << endl;
|
||||
cout << "Operation count for linear complexity (array traversal) = " << count << endl;
|
||||
|
||||
count = quadratic(n);
|
||||
cout << "Quadratic order operation count = " << count << endl;
|
||||
cout << "Operation count for quadratic complexity = " << 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 << "Quadratic order (bubble sort) operation count = " << count << endl;
|
||||
cout << "Operation count for quadratic complexity (bubble sort) = " << count << endl;
|
||||
|
||||
count = exponential(n);
|
||||
cout << "Exponential order (loop implementation) operation count = " << count << endl;
|
||||
cout << "Operation count for exponential complexity (iterative implementation) = " << count << endl;
|
||||
count = expRecur(n);
|
||||
cout << "Exponential order (recursive implementation) operation count = " << count << endl;
|
||||
cout << "Operation count for exponential complexity (recursive implementation) = " << count << endl;
|
||||
|
||||
count = logarithmic(n);
|
||||
cout << "Logarithmic order (loop implementation) operation count = " << count << endl;
|
||||
cout << "Operation count for logarithmic complexity (iterative implementation) = " << count << endl;
|
||||
count = logRecur(n);
|
||||
cout << "Logarithmic order (recursive implementation) operation count = " << count << endl;
|
||||
cout << "Operation count for logarithmic complexity (recursive implementation) = " << count << endl;
|
||||
|
||||
count = linearLogRecur(n);
|
||||
cout << "Linearithmic order (recursive implementation) operation count = " << count << endl;
|
||||
cout << "Operation count for linearithmic complexity (recursive implementation) = " << count << endl;
|
||||
|
||||
count = factorialRecur(n);
|
||||
cout << "Factorial order (recursive implementation) operation count = " << count << endl;
|
||||
cout << "Operation count for factorial complexity (recursive implementation) = " << count << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -6,32 +6,32 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Generate an array with elements { 1, 2, ..., n }, order shuffled */
|
||||
/* Generate an array containing { 1, 2, ..., n } in shuffled order */
|
||||
vector<int> randomNumbers(int n) {
|
||||
vector<int> nums(n);
|
||||
// Generate array nums = { 1, 2, 3, ..., n }
|
||||
// Generate the array nums = { 1, 2, 3, ..., n }
|
||||
for (int i = 0; i < n; i++) {
|
||||
nums[i] = i + 1;
|
||||
}
|
||||
// Use system time to generate random seed
|
||||
// Use the system time to generate a random seed
|
||||
unsigned seed = chrono::system_clock::now().time_since_epoch().count();
|
||||
// Randomly shuffle array elements
|
||||
// Randomly shuffle the array elements
|
||||
shuffle(nums.begin(), nums.end(), default_random_engine(seed));
|
||||
return nums;
|
||||
}
|
||||
|
||||
/* Find the index of number 1 in array nums */
|
||||
/* Find the index of the number 1 in array nums */
|
||||
int findOne(vector<int> &nums) {
|
||||
for (int i = 0; i < nums.size(); i++) {
|
||||
// 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
|
||||
// When 1 is at the start of the array, the best-case time complexity is O(1)
|
||||
// When 1 is at the end of the array, the worst-case time complexity is O(n)
|
||||
if (nums[i] == 1)
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
int n = 100;
|
||||
@@ -39,7 +39,7 @@ int main() {
|
||||
int index = findOne(nums);
|
||||
cout << "\nArray [ 1, 2, ..., n ] after shuffling = ";
|
||||
printVector(nums);
|
||||
cout << "Index of number 1 is " << index << endl;
|
||||
cout << "The index of the 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, it means there is no target element, return -1
|
||||
// If the interval is empty, the target is absent; return -1
|
||||
if (i > j) {
|
||||
return -1;
|
||||
}
|
||||
// Calculate the midpoint index m
|
||||
int m = (i + j) / 2;
|
||||
if (nums[m] < target) {
|
||||
// Recursion subproblem f(m+1, j)
|
||||
// Recurse on subproblem f(m+1, j)
|
||||
return dfs(nums, target, m + 1, j);
|
||||
} else if (nums[m] > target) {
|
||||
// Recursion subproblem f(i, m-1)
|
||||
// Recurse on subproblem f(i, m-1)
|
||||
return dfs(nums, target, i, m - 1);
|
||||
} else {
|
||||
// Found the target element, return its index
|
||||
// The target element was found; return its index
|
||||
return m;
|
||||
}
|
||||
}
|
||||
@@ -29,16 +29,16 @@ 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 the problem f(0, n-1)
|
||||
// Solve problem f(0, n-1)
|
||||
return dfs(nums, target, 0, n - 1);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int target = 6;
|
||||
vector<int> nums = {1, 3, 6, 8, 12, 15, 23, 26, 31, 35};
|
||||
|
||||
// Binary search (closed interval on both sides)
|
||||
// Binary search (closed interval)
|
||||
int index = binarySearch(nums, target);
|
||||
cout << "Index of target element 6 = " << index << endl;
|
||||
|
||||
|
||||
@@ -6,14 +6,14 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Build binary tree: divide and conquer */
|
||||
/* Build a binary tree: divide and conquer */
|
||||
TreeNode *dfs(vector<int> &preorder, unordered_map<int, int> &inorderMap, int i, int l, int r) {
|
||||
// Terminate when the subtree interval is empty
|
||||
// Stop when the subtree interval is empty
|
||||
if (r - l < 0)
|
||||
return NULL;
|
||||
// Initialize the root node
|
||||
TreeNode *root = new TreeNode(preorder[i]);
|
||||
// Query m to divide the left and right subtrees
|
||||
// Look up m to separate the left and right subtrees
|
||||
int m = inorderMap[preorder[i]];
|
||||
// Subproblem: build the left subtree
|
||||
root->left = dfs(preorder, inorderMap, i + 1, l, m - 1);
|
||||
@@ -23,9 +23,9 @@ TreeNode *dfs(vector<int> &preorder, unordered_map<int, int> &inorderMap, int i,
|
||||
return root;
|
||||
}
|
||||
|
||||
/* Build binary tree */
|
||||
/* Build a binary tree */
|
||||
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
|
||||
// Initialize hash map, storing the mapping from inorder elements to indices
|
||||
// Initialize a hash table mapping each element in inorder to its index
|
||||
unordered_map<int, int> inorderMap;
|
||||
for (int i = 0; i < inorder.size(); i++) {
|
||||
inorderMap[inorder[i]] = i;
|
||||
@@ -34,7 +34,7 @@ TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
|
||||
return root;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
vector<int> preorder = {3, 9, 2, 1, 7};
|
||||
vector<int> inorder = {9, 3, 1, 2, 7};
|
||||
@@ -44,7 +44,7 @@ int main() {
|
||||
printVector(inorder);
|
||||
|
||||
TreeNode *root = buildTree(preorder, inorder);
|
||||
cout << "The constructed binary tree is:\n";
|
||||
cout << "Constructed binary tree:\n";
|
||||
printTree(root);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
#include <cassert>
|
||||
|
||||
/* Exponentiation by squaring */
|
||||
/* Fast exponentiation */
|
||||
int fastPow(int x, int n) {
|
||||
if (n == 0) {
|
||||
return 1;
|
||||
|
||||
@@ -6,9 +6,9 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Move a disk */
|
||||
/* Move one disk */
|
||||
void move(vector<int> &src, vector<int> &tar) {
|
||||
// Take out a disk from the top of src
|
||||
// Take a disk from the top of src
|
||||
int pan = src.back();
|
||||
src.pop_back();
|
||||
// Place the disk on top of tar
|
||||
@@ -17,14 +17,14 @@ void move(vector<int> &src, vector<int> &tar) {
|
||||
|
||||
/* Solve the Tower of Hanoi problem f(i) */
|
||||
void dfs(int i, vector<int> &src, vector<int> &buf, vector<int> &tar) {
|
||||
// If there is only one disk left in src, move it directly to tar
|
||||
// If only one disk remains to be moved from src, move it directly to tar
|
||||
if (i == 1) {
|
||||
move(src, tar);
|
||||
return;
|
||||
}
|
||||
// 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 disk from src to tar
|
||||
// Subproblem f(1): move the remaining disk of this subproblem from src to tar
|
||||
move(src, tar);
|
||||
// Subproblem f(i-1): move the top i-1 disks from buf to tar using src
|
||||
dfs(i - 1, buf, src, tar);
|
||||
@@ -37,9 +37,9 @@ void solveHanota(vector<int> &A, vector<int> &B, vector<int> &C) {
|
||||
dfs(n, A, B, C);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
// The tail of the list is the top of the rod
|
||||
// The end of each list represents the top of the peg
|
||||
vector<int> A = {5, 4, 3, 2, 1};
|
||||
vector<int> B = {};
|
||||
vector<int> C = {};
|
||||
@@ -54,7 +54,7 @@ int main() {
|
||||
|
||||
solveHanota(A, B, C);
|
||||
|
||||
cout << "After disk movement:\n";
|
||||
cout << "After moving all disks:\n";
|
||||
cout << "A =";
|
||||
printVector(A);
|
||||
cout << "B =";
|
||||
|
||||
@@ -9,35 +9,35 @@
|
||||
|
||||
/* Backtracking */
|
||||
void backtrack(vector<int> &choices, int state, int n, vector<int> &res) {
|
||||
// When climbing to the n-th stair, add 1 to the solution count
|
||||
// When step n is reached, increase the number of ways by 1
|
||||
if (state == n)
|
||||
res[0]++;
|
||||
// Traverse all choices
|
||||
// Iterate over all choices
|
||||
for (auto &choice : choices) {
|
||||
// Pruning: not allowed to go beyond the n-th stair
|
||||
// Prune: do not go beyond step n
|
||||
if (state + choice > n)
|
||||
continue;
|
||||
// Attempt: make choice, update state
|
||||
// Try: make a choice and update the state
|
||||
backtrack(choices, state + choice, n, res);
|
||||
// Backtrack
|
||||
}
|
||||
}
|
||||
|
||||
/* Climbing stairs: Backtracking */
|
||||
/* Climbing stairs: backtracking */
|
||||
int climbingStairsBacktrack(int n) {
|
||||
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
|
||||
vector<int> choices = {1, 2}; // Choose to climb 1 or 2 steps
|
||||
int state = 0; // Start climbing from step 0
|
||||
vector<int> res = {0}; // Use res[0] to record the number of ways
|
||||
backtrack(choices, state, n, res);
|
||||
return res[0];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsBacktrack(n);
|
||||
cout << "Climbing " << n << " stairs has " << res << " solutions" << endl;
|
||||
cout << "Climbing " << n << " stairs: " << res << " ways" << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -6,19 +6,19 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Climbing stairs with constraint: Dynamic programming */
|
||||
/* Climbing stairs with constraints: dynamic programming */
|
||||
int climbingStairsConstraintDP(int n) {
|
||||
if (n == 1 || n == 2) {
|
||||
return 1;
|
||||
}
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
// Initialize the dp table to store subproblem solutions
|
||||
vector<vector<int>> dp(n + 1, vector<int>(3, 0));
|
||||
// Initial state: preset the solution to the smallest subproblem
|
||||
// Initial states: set the solutions to the smallest subproblems
|
||||
dp[1][1] = 1;
|
||||
dp[1][2] = 0;
|
||||
dp[2][1] = 0;
|
||||
dp[2][2] = 1;
|
||||
// State transition: gradually solve larger subproblems from smaller ones
|
||||
// State transitions: solve progressively larger subproblems using smaller ones
|
||||
for (int i = 3; i <= n; i++) {
|
||||
dp[i][1] = dp[i - 1][2];
|
||||
dp[i][2] = dp[i - 2][1] + dp[i - 2][2];
|
||||
@@ -26,12 +26,12 @@ int climbingStairsConstraintDP(int n) {
|
||||
return dp[n][1] + dp[n][2];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsConstraintDP(n);
|
||||
cout << "Climbing " << n << " stairs has " << res << " solutions" << endl;
|
||||
cout << "Climbing " << n << " stairs: " << res << " ways" << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
/* Search */
|
||||
int dfs(int i) {
|
||||
// Known dp[1] and dp[2], return them
|
||||
// The values of dp[1] and dp[2] are known; return them
|
||||
if (i == 1 || i == 2)
|
||||
return i;
|
||||
// dp[i] = dp[i-1] + dp[i-2]
|
||||
@@ -16,17 +16,17 @@ int dfs(int i) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Climbing stairs: Search */
|
||||
/* Climbing stairs: search */
|
||||
int climbingStairsDFS(int n) {
|
||||
return dfs(n);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsDFS(n);
|
||||
cout << "Climbing " << n << " stairs has " << res << " solutions" << endl;
|
||||
cout << "Climbing " << n << " stairs: " << res << " ways" << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -6,12 +6,12 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Memoization search */
|
||||
/* Memoized search */
|
||||
int dfs(int i, vector<int> &mem) {
|
||||
// Known dp[1] and dp[2], return them
|
||||
// The values of dp[1] and dp[2] are known; return them
|
||||
if (i == 1 || i == 2)
|
||||
return i;
|
||||
// If record dp[i] exists, return it directly
|
||||
// If dp[i] has been recorded, return it directly
|
||||
if (mem[i] != -1)
|
||||
return mem[i];
|
||||
// dp[i] = dp[i-1] + dp[i-2]
|
||||
@@ -21,19 +21,19 @@ int dfs(int i, vector<int> &mem) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Climbing stairs: Memoization search */
|
||||
/* Climbing stairs: memoized search */
|
||||
int climbingStairsDFSMem(int n) {
|
||||
// mem[i] records the total number of solutions to climb to the i-th stair, -1 means no record
|
||||
// mem[i] stores the number of ways to reach step i; -1 means no result has been recorded
|
||||
vector<int> mem(n + 1, -1);
|
||||
return dfs(n, mem);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsDFSMem(n);
|
||||
cout << "Climbing " << n << " stairs has " << res << " solutions" << endl;
|
||||
cout << "Climbing " << n << " stairs: " << res << " ways" << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -6,23 +6,23 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Climbing stairs: Dynamic programming */
|
||||
/* Climbing stairs: dynamic programming */
|
||||
int climbingStairsDP(int n) {
|
||||
if (n == 1 || n == 2)
|
||||
return n;
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
// Initialize the dp table to store subproblem solutions
|
||||
vector<int> dp(n + 1);
|
||||
// Initial state: preset the solution to the smallest subproblem
|
||||
// Initial states: set the solutions to the smallest subproblems
|
||||
dp[1] = 1;
|
||||
dp[2] = 2;
|
||||
// State transition: gradually solve larger subproblems from smaller ones
|
||||
// State transitions: solve progressively larger subproblems using smaller ones
|
||||
for (int i = 3; i <= n; i++) {
|
||||
dp[i] = dp[i - 1] + dp[i - 2];
|
||||
}
|
||||
return dp[n];
|
||||
}
|
||||
|
||||
/* Climbing stairs: Space-optimized dynamic programming */
|
||||
/* Climbing stairs: space-optimized dynamic programming */
|
||||
int climbingStairsDPComp(int n) {
|
||||
if (n == 1 || n == 2)
|
||||
return n;
|
||||
@@ -35,15 +35,15 @@ int climbingStairsDPComp(int n) {
|
||||
return b;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsDP(n);
|
||||
cout << "Climbing " << n << " stairs has " << res << " solutions" << endl;
|
||||
cout << "Climbing " << n << " stairs: " << res << " ways" << endl;
|
||||
|
||||
res = climbingStairsDPComp(n);
|
||||
cout << "Climbing " << n << " stairs has " << res << " solutions" << endl;
|
||||
cout << "Climbing " << n << " stairs: " << res << " ways" << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -6,24 +6,24 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Coin change: Dynamic programming */
|
||||
/* Coin change: dynamic programming */
|
||||
int coinChangeDP(vector<int> &coins, int amt) {
|
||||
int n = coins.size();
|
||||
int MAX = amt + 1;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
vector<vector<int>> dp(n + 1, vector<int>(amt + 1, 0));
|
||||
// State transition: first row and first column
|
||||
// State transitions: first row and first column
|
||||
for (int a = 1; a <= amt; a++) {
|
||||
dp[0][a] = MAX;
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
// State transitions: remaining rows and columns
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// If exceeds target amount, don't select coin i
|
||||
// If the coin exceeds the target amount, do not choose coin i
|
||||
dp[i][a] = dp[i - 1][a];
|
||||
} else {
|
||||
// The smaller value between not selecting and selecting coin i
|
||||
// Take the smaller result of not choosing and choosing coin i
|
||||
dp[i][a] = min(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1);
|
||||
}
|
||||
}
|
||||
@@ -31,21 +31,21 @@ int coinChangeDP(vector<int> &coins, int amt) {
|
||||
return dp[n][amt] != MAX ? dp[n][amt] : -1;
|
||||
}
|
||||
|
||||
/* Coin change: Space-optimized dynamic programming */
|
||||
/* Coin change: space-optimized dynamic programming */
|
||||
int coinChangeDPComp(vector<int> &coins, int amt) {
|
||||
int n = coins.size();
|
||||
int MAX = amt + 1;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
vector<int> dp(amt + 1, MAX);
|
||||
dp[0] = 0;
|
||||
// State transition
|
||||
// State transitions
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// If exceeds target amount, don't select coin i
|
||||
// If the coin exceeds the target amount, do not choose coin i
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// The smaller value between not selecting and selecting coin i
|
||||
// Take the smaller result of not choosing and choosing coin i
|
||||
dp[a] = min(dp[a], dp[a - coins[i - 1]] + 1);
|
||||
}
|
||||
}
|
||||
@@ -60,11 +60,11 @@ int main() {
|
||||
|
||||
// Dynamic programming
|
||||
int res = coinChangeDP(coins, amt);
|
||||
cout << "Minimum number of coins needed to make target amount is " << res << endl;
|
||||
cout << "Minimum number of coins needed to reach the target amount: " << res << endl;
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = coinChangeDPComp(coins, amt);
|
||||
cout << "Minimum number of coins needed to make target amount is " << res << endl;
|
||||
cout << "Minimum number of coins needed to reach the target amount: " << res << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -6,23 +6,23 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Coin change II: Dynamic programming */
|
||||
/* Coin change II: dynamic programming */
|
||||
int coinChangeIIDP(vector<int> &coins, int amt) {
|
||||
int n = coins.size();
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
vector<vector<int>> dp(n + 1, vector<int>(amt + 1, 0));
|
||||
// Initialize first column
|
||||
// Initialize the first column
|
||||
for (int i = 0; i <= n; i++) {
|
||||
dp[i][0] = 1;
|
||||
}
|
||||
// State transition
|
||||
// State transitions
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// If exceeds target amount, don't select coin i
|
||||
// If the coin exceeds the target amount, do not choose coin i
|
||||
dp[i][a] = dp[i - 1][a];
|
||||
} else {
|
||||
// Sum of the two options: not selecting and selecting coin i
|
||||
// Add the numbers of ways without and with coin i
|
||||
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]];
|
||||
}
|
||||
}
|
||||
@@ -30,20 +30,20 @@ int coinChangeIIDP(vector<int> &coins, int amt) {
|
||||
return dp[n][amt];
|
||||
}
|
||||
|
||||
/* Coin change II: Space-optimized dynamic programming */
|
||||
/* Coin change II: space-optimized dynamic programming */
|
||||
int coinChangeIIDPComp(vector<int> &coins, int amt) {
|
||||
int n = coins.size();
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
vector<int> dp(amt + 1, 0);
|
||||
dp[0] = 1;
|
||||
// State transition
|
||||
// State transitions
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// If exceeds target amount, don't select coin i
|
||||
// If the coin exceeds the target amount, do not choose coin i
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// Sum of the two options: not selecting and selecting coin i
|
||||
// Add the numbers of ways without and with coin i
|
||||
dp[a] = dp[a] + dp[a - coins[i - 1]];
|
||||
}
|
||||
}
|
||||
@@ -58,11 +58,11 @@ int main() {
|
||||
|
||||
// Dynamic programming
|
||||
int res = coinChangeIIDP(coins, amt);
|
||||
cout << "Number of coin combinations to make target amount is " << res << endl;
|
||||
cout << "Number of coin combinations that make the target amount: " << res << endl;
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = coinChangeIIDPComp(coins, amt);
|
||||
cout << "Number of coin combinations to make target amount is " << res << endl;
|
||||
cout << "Number of coin combinations that make the target amount: " << res << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -6,73 +6,73 @@
|
||||
|
||||
#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 both prefixes s[0:i] and t[0:j] are empty, return 0
|
||||
if (i == 0 && j == 0)
|
||||
return 0;
|
||||
// If s is empty, return length of t
|
||||
// If the prefix s[0:i] is empty, return j, the length of t[0:j]
|
||||
if (i == 0)
|
||||
return j;
|
||||
// If t is empty, return length of s
|
||||
// If the prefix t[0:j] is empty, return i, the length of s[0:i]
|
||||
if (j == 0)
|
||||
return i;
|
||||
// If two characters are equal, skip both characters
|
||||
// If the two characters are equal, skip both of them
|
||||
if (s[i - 1] == t[j - 1])
|
||||
return editDistanceDFS(s, t, i - 1, j - 1);
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
|
||||
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 minimum edit steps
|
||||
// Return the minimum number of edits
|
||||
return min(min(insert, del), replace) + 1;
|
||||
}
|
||||
|
||||
/* Edit distance: Memoization search */
|
||||
/* Edit distance: memoized 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 both prefixes s[0:i] and t[0:j] are empty, return 0
|
||||
if (i == 0 && j == 0)
|
||||
return 0;
|
||||
// If s is empty, return length of t
|
||||
// If the prefix s[0:i] is empty, return j, the length of t[0:j]
|
||||
if (i == 0)
|
||||
return j;
|
||||
// If t is empty, return length of s
|
||||
// If the prefix t[0:j] is empty, return i, the length of s[0:i]
|
||||
if (j == 0)
|
||||
return i;
|
||||
// If there's a record, return it directly
|
||||
// If a result has already been recorded, return it directly
|
||||
if (mem[i][j] != -1)
|
||||
return mem[i][j];
|
||||
// If two characters are equal, skip both characters
|
||||
// If the two characters are equal, skip both of them
|
||||
if (s[i - 1] == t[j - 1])
|
||||
return editDistanceDFSMem(s, t, mem, i - 1, j - 1);
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
|
||||
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 minimum edit steps
|
||||
// Record and return the minimum number of edits
|
||||
mem[i][j] = min(min(insert, del), replace) + 1;
|
||||
return mem[i][j];
|
||||
}
|
||||
|
||||
/* Edit distance: Dynamic programming */
|
||||
/* Edit distance: dynamic programming */
|
||||
int editDistanceDP(string s, string t) {
|
||||
int n = s.length(), m = t.length();
|
||||
vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
|
||||
// State transition: first row and first column
|
||||
// State transitions: first row and first column
|
||||
for (int i = 1; i <= n; i++) {
|
||||
dp[i][0] = i;
|
||||
}
|
||||
for (int j = 1; j <= m; j++) {
|
||||
dp[0][j] = j;
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
// State transitions: remaining 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 two characters are equal, skip both characters
|
||||
// If the two characters are equal, skip both of them
|
||||
dp[i][j] = dp[i - 1][j - 1];
|
||||
} else {
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
|
||||
dp[i][j] = min(min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
|
||||
}
|
||||
}
|
||||
@@ -80,36 +80,36 @@ int editDistanceDP(string s, string t) {
|
||||
return dp[n][m];
|
||||
}
|
||||
|
||||
/* Edit distance: Space-optimized dynamic programming */
|
||||
/* Edit distance: space-optimized dynamic programming */
|
||||
int editDistanceDPComp(string s, string t) {
|
||||
int n = s.length(), m = t.length();
|
||||
vector<int> dp(m + 1, 0);
|
||||
// State transition: first row
|
||||
// State transitions: first row
|
||||
for (int j = 1; j <= m; j++) {
|
||||
dp[j] = j;
|
||||
}
|
||||
// State transition: rest of the rows
|
||||
// State transitions: remaining rows
|
||||
for (int i = 1; i <= n; i++) {
|
||||
// State transition: first column
|
||||
// State transitions: first column
|
||||
int leftup = dp[0]; // Temporarily store dp[i-1, j-1]
|
||||
dp[0] = i;
|
||||
// State transition: rest of the columns
|
||||
// State transitions: remaining columns
|
||||
for (int j = 1; j <= m; j++) {
|
||||
int temp = dp[j];
|
||||
if (s[i - 1] == t[j - 1]) {
|
||||
// If two characters are equal, skip both characters
|
||||
// If the two characters are equal, skip both of them
|
||||
dp[j] = leftup;
|
||||
} else {
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
|
||||
dp[j] = min(min(dp[j - 1], dp[j]), leftup) + 1;
|
||||
}
|
||||
leftup = temp; // Update for next round's dp[i-1, j-1]
|
||||
leftup = temp; // Update to dp[i-1, j-1] for the next iteration
|
||||
}
|
||||
}
|
||||
return dp[m];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
string s = "bag";
|
||||
string t = "pack";
|
||||
@@ -117,20 +117,20 @@ int main() {
|
||||
|
||||
// Brute-force search
|
||||
int res = editDistanceDFS(s, t, n, m);
|
||||
cout << "Changing " << s << " to " << t << " requires a minimum of " << res << " edits";
|
||||
cout << "Changing " << s << " to " << t << " requires at least " << res << " edits\n";
|
||||
|
||||
// Memoization search
|
||||
// Memoized 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";
|
||||
cout << "Changing " << s << " to " << t << " requires at least " << res << " edits\n";
|
||||
|
||||
// Dynamic programming
|
||||
res = editDistanceDP(s, t);
|
||||
cout << "Changing " << s << " to " << t << " requires a minimum of " << res << " edits";
|
||||
cout << "Changing " << s << " to " << t << " requires at least " << res << " edits\n";
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = editDistanceDPComp(s, t);
|
||||
cout << "Changing " << s << " to " << t << " requires a minimum of " << res << " edits";
|
||||
cout << "Changing " << s << " to " << t << " requires at least " << res << " edits\n";
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -4,58 +4,58 @@
|
||||
|
||||
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 selected or knapsack has no remaining capacity, return value 0
|
||||
// If all items have been considered or no capacity remains, return value 0
|
||||
if (i == 0 || c == 0) {
|
||||
return 0;
|
||||
}
|
||||
// If exceeds knapsack capacity, can only choose not to put it in
|
||||
// If the item exceeds the remaining capacity, it must be excluded
|
||||
if (wgt[i - 1] > c) {
|
||||
return knapsackDFS(wgt, val, i - 1, c);
|
||||
}
|
||||
// Calculate the maximum value of not putting in and putting in item i
|
||||
// Calculate the maximum values obtained by excluding and including item i
|
||||
int no = knapsackDFS(wgt, val, i - 1, c);
|
||||
int yes = knapsackDFS(wgt, val, i - 1, c - wgt[i - 1]) + val[i - 1];
|
||||
// Return the larger value of the two options
|
||||
// Return the larger value from the two choices
|
||||
return max(no, yes);
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Memoization search */
|
||||
/* 0-1 knapsack: memoized search */
|
||||
int knapsackDFSMem(vector<int> &wgt, vector<int> &val, vector<vector<int>> &mem, int i, int c) {
|
||||
// If all items have been selected or knapsack has no remaining capacity, return value 0
|
||||
// If all items have been considered or no capacity remains, return value 0
|
||||
if (i == 0 || c == 0) {
|
||||
return 0;
|
||||
}
|
||||
// If there's a record, return it directly
|
||||
// If a result has already been recorded, return it directly
|
||||
if (mem[i][c] != -1) {
|
||||
return mem[i][c];
|
||||
}
|
||||
// If exceeds knapsack capacity, can only choose not to put it in
|
||||
// If the item exceeds the remaining capacity, it must be excluded
|
||||
if (wgt[i - 1] > c) {
|
||||
return knapsackDFSMem(wgt, val, mem, i - 1, c);
|
||||
}
|
||||
// Calculate the maximum value of not putting in and putting in item i
|
||||
// Calculate the maximum values obtained by excluding and including item i
|
||||
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 larger value of the two options
|
||||
// Record and return the larger value from the two choices
|
||||
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
|
||||
// Initialize the dp table
|
||||
vector<vector<int>> dp(n + 1, vector<int>(cap + 1, 0));
|
||||
// State transition
|
||||
// State transitions
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int c = 1; c <= cap; c++) {
|
||||
if (wgt[i - 1] > c) {
|
||||
// If exceeds knapsack capacity, don't select item i
|
||||
// If item i exceeds the remaining capacity, do not choose it
|
||||
dp[i][c] = dp[i - 1][c];
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
dp[i][c] = max(dp[i - 1][c], dp[i - 1][c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
@@ -63,17 +63,17 @@ 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
|
||||
// Initialize the dp table
|
||||
vector<int> dp(cap + 1, 0);
|
||||
// State transition
|
||||
// State transitions
|
||||
for (int i = 1; i <= n; i++) {
|
||||
// Traverse in reverse order
|
||||
// Traverse in decreasing order
|
||||
for (int c = cap; c >= 1; c--) {
|
||||
if (wgt[i - 1] <= c) {
|
||||
// The larger value between not selecting and selecting item i
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
dp[c] = max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
@@ -81,7 +81,7 @@ int knapsackDPComp(vector<int> &wgt, vector<int> &val, int cap) {
|
||||
return dp[cap];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
vector<int> wgt = {10, 20, 30, 40, 50};
|
||||
vector<int> val = {50, 120, 150, 210, 240};
|
||||
@@ -90,20 +90,20 @@ int main() {
|
||||
|
||||
// Brute-force search
|
||||
int res = knapsackDFS(wgt, val, n, cap);
|
||||
cout << "Maximum item value not exceeding knapsack capacity is " << res << endl;
|
||||
cout << "Maximum total item value within the knapsack capacity: " << res << endl;
|
||||
|
||||
// Memoization search
|
||||
// Memoized search
|
||||
vector<vector<int>> mem(n + 1, vector<int>(cap + 1, -1));
|
||||
res = knapsackDFSMem(wgt, val, mem, n, cap);
|
||||
cout << "Maximum item value not exceeding knapsack capacity is " << res << endl;
|
||||
cout << "Maximum total item value within the knapsack capacity: " << res << endl;
|
||||
|
||||
// Dynamic programming
|
||||
res = knapsackDP(wgt, val, cap);
|
||||
cout << "Maximum item value not exceeding knapsack capacity is " << res << endl;
|
||||
cout << "Maximum total item value within the knapsack capacity: " << res << endl;
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = knapsackDPComp(wgt, val, cap);
|
||||
cout << "Maximum item value not exceeding knapsack capacity is " << res << endl;
|
||||
cout << "Maximum total item value within the knapsack capacity: " << res << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -6,24 +6,24 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Minimum cost climbing stairs: Dynamic programming */
|
||||
/* Minimum cost to climb 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 solutions to subproblems
|
||||
// Initialize the dp table to store subproblem solutions
|
||||
vector<int> dp(n + 1);
|
||||
// Initial state: preset the solution to the smallest subproblem
|
||||
// Initial states: set the solutions to the smallest subproblems
|
||||
dp[1] = cost[1];
|
||||
dp[2] = cost[2];
|
||||
// State transition: gradually solve larger subproblems from smaller ones
|
||||
// State transitions: solve progressively larger subproblems using smaller ones
|
||||
for (int i = 3; i <= n; i++) {
|
||||
dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i];
|
||||
}
|
||||
return dp[n];
|
||||
}
|
||||
|
||||
/* Minimum cost climbing stairs: Space-optimized dynamic programming */
|
||||
/* Minimum cost to climb stairs: space-optimized dynamic programming */
|
||||
int minCostClimbingStairsDPComp(vector<int> &cost) {
|
||||
int n = cost.size() - 1;
|
||||
if (n == 1 || n == 2)
|
||||
@@ -37,17 +37,17 @@ int minCostClimbingStairsDPComp(vector<int> &cost) {
|
||||
return b;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
vector<int> cost = {0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1};
|
||||
cout << "Input stair cost list is ";
|
||||
cout << "Input stair cost list: ";
|
||||
printVector(cost);
|
||||
|
||||
int res = minCostClimbingStairsDP(cost);
|
||||
cout << "Minimum cost to climb stairs is " << res << endl;
|
||||
cout << "Minimum cost to climb the stairs: " << res << endl;
|
||||
|
||||
res = minCostClimbingStairsDPComp(cost);
|
||||
cout << "Minimum cost to climb stairs is " << res << endl;
|
||||
cout << "Minimum cost to climb the stairs: " << res << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -6,60 +6,60 @@
|
||||
|
||||
#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
|
||||
// Stop searching at the top-left cell
|
||||
if (i == 0 && j == 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// If row or column index is out of bounds, return +∞ cost
|
||||
// If a row or column index is out of bounds, return a cost of +∞
|
||||
if (i < 0 || j < 0) {
|
||||
return INT_MAX;
|
||||
}
|
||||
// Calculate the minimum path cost from top-left to (i-1, j) and (i, j-1)
|
||||
// Calculate the minimum path costs from the top-left corner to (i-1, j) and (i, j-1)
|
||||
int up = minPathSumDFS(grid, i - 1, j);
|
||||
int left = minPathSumDFS(grid, i, j - 1);
|
||||
// Return the minimum path cost from top-left to (i, j)
|
||||
// Return the minimum path cost from the top-left corner to (i, j)
|
||||
return min(left, up) != INT_MAX ? min(left, up) + grid[i][j] : INT_MAX;
|
||||
}
|
||||
|
||||
/* Minimum path sum: Memoization search */
|
||||
/* Minimum path sum: memoized 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
|
||||
// Stop searching at the top-left cell
|
||||
if (i == 0 && j == 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// If row or column index is out of bounds, return +∞ cost
|
||||
// If a row or column index is out of bounds, return a cost of +∞
|
||||
if (i < 0 || j < 0) {
|
||||
return INT_MAX;
|
||||
}
|
||||
// If there's a record, return it directly
|
||||
// If a result has already been recorded, return it directly
|
||||
if (mem[i][j] != -1) {
|
||||
return mem[i][j];
|
||||
}
|
||||
// Minimum path cost for left and upper cells
|
||||
// Minimum path costs to the cells on the left and above
|
||||
int up = minPathSumDFSMem(grid, mem, i - 1, j);
|
||||
int left = minPathSumDFSMem(grid, mem, i, j - 1);
|
||||
// Record and return the minimum path cost from top-left to (i, j)
|
||||
// Record and return the minimum path cost from the top-left corner to (i, j)
|
||||
mem[i][j] = min(left, up) != INT_MAX ? min(left, up) + grid[i][j] : INT_MAX;
|
||||
return mem[i][j];
|
||||
}
|
||||
|
||||
/* Minimum path sum: Dynamic programming */
|
||||
/* Minimum path sum: dynamic programming */
|
||||
int minPathSumDP(vector<vector<int>> &grid) {
|
||||
int n = grid.size(), m = grid[0].size();
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
vector<vector<int>> dp(n, vector<int>(m));
|
||||
dp[0][0] = grid[0][0];
|
||||
// State transition: first row
|
||||
// State transitions: first row
|
||||
for (int j = 1; j < m; j++) {
|
||||
dp[0][j] = dp[0][j - 1] + grid[0][j];
|
||||
}
|
||||
// State transition: first column
|
||||
// State transitions: first column
|
||||
for (int i = 1; i < n; i++) {
|
||||
dp[i][0] = dp[i - 1][0] + grid[i][0];
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
// State transitions: remaining rows and columns
|
||||
for (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];
|
||||
@@ -68,21 +68,21 @@ int minPathSumDP(vector<vector<int>> &grid) {
|
||||
return dp[n - 1][m - 1];
|
||||
}
|
||||
|
||||
/* Minimum path sum: Space-optimized dynamic programming */
|
||||
/* Minimum path sum: space-optimized dynamic programming */
|
||||
int minPathSumDPComp(vector<vector<int>> &grid) {
|
||||
int n = grid.size(), m = grid[0].size();
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
vector<int> dp(m);
|
||||
// State transition: first row
|
||||
// State transitions: first row
|
||||
dp[0] = grid[0][0];
|
||||
for (int j = 1; j < m; j++) {
|
||||
dp[j] = dp[j - 1] + grid[0][j];
|
||||
}
|
||||
// State transition: rest of the rows
|
||||
// State transitions: remaining rows
|
||||
for (int i = 1; i < n; i++) {
|
||||
// State transition: first column
|
||||
// State transitions: first column
|
||||
dp[0] = dp[0] + grid[i][0];
|
||||
// State transition: rest of the columns
|
||||
// State transitions: remaining columns
|
||||
for (int j = 1; j < m; j++) {
|
||||
dp[j] = min(dp[j - 1], dp[j]) + grid[i][j];
|
||||
}
|
||||
@@ -90,27 +90,27 @@ int minPathSumDPComp(vector<vector<int>> &grid) {
|
||||
return dp[m - 1];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
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
|
||||
int res = minPathSumDFS(grid, n - 1, m - 1);
|
||||
cout << "Minimum path sum from top-left to bottom-right is " << res << endl;
|
||||
cout << "Minimum path sum from the top-left to the bottom-right corner: " << res << endl;
|
||||
|
||||
// Memoization search
|
||||
// Memoized search
|
||||
vector<vector<int>> mem(n, vector<int>(m, -1));
|
||||
res = minPathSumDFSMem(grid, mem, n - 1, m - 1);
|
||||
cout << "Minimum path sum from top-left to bottom-right is " << res << endl;
|
||||
cout << "Minimum path sum from the top-left to the bottom-right corner: " << res << endl;
|
||||
|
||||
// Dynamic programming
|
||||
res = minPathSumDP(grid);
|
||||
cout << "Minimum path sum from top-left to bottom-right is " << res << endl;
|
||||
cout << "Minimum path sum from the top-left to the bottom-right corner: " << res << endl;
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = minPathSumDPComp(grid);
|
||||
cout << "Minimum path sum from top-left to bottom-right is " << res << endl;
|
||||
cout << "Minimum path sum from the top-left to the bottom-right corner: " << res << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -6,19 +6,19 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Unbounded knapsack: Dynamic programming */
|
||||
/* Unbounded knapsack: dynamic programming */
|
||||
int unboundedKnapsackDP(vector<int> &wgt, vector<int> &val, int cap) {
|
||||
int n = wgt.size();
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
vector<vector<int>> dp(n + 1, vector<int>(cap + 1, 0));
|
||||
// State transition
|
||||
// State transitions
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int c = 1; c <= cap; c++) {
|
||||
if (wgt[i - 1] > c) {
|
||||
// If exceeds knapsack capacity, don't select item i
|
||||
// If item i exceeds the remaining capacity, do not choose it
|
||||
dp[i][c] = dp[i - 1][c];
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
dp[i][c] = max(dp[i - 1][c], dp[i][c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
@@ -26,19 +26,19 @@ int unboundedKnapsackDP(vector<int> &wgt, vector<int> &val, int cap) {
|
||||
return dp[n][cap];
|
||||
}
|
||||
|
||||
/* Unbounded 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
|
||||
// Initialize the dp table
|
||||
vector<int> dp(cap + 1, 0);
|
||||
// State transition
|
||||
// State transitions
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int c = 1; c <= cap; c++) {
|
||||
if (wgt[i - 1] > c) {
|
||||
// If exceeds knapsack capacity, don't select item i
|
||||
// If item i exceeds the remaining capacity, do not choose it
|
||||
dp[c] = dp[c];
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
dp[c] = 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 << "Maximum item value not exceeding knapsack capacity is " << res << endl;
|
||||
cout << "Maximum total item value within the knapsack capacity: " << res << endl;
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = unboundedKnapsackDPComp(wgt, val, cap);
|
||||
cout << "Maximum item value not exceeding knapsack capacity is " << res << endl;
|
||||
cout << "Maximum total item value within the knapsack capacity: " << res << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -6,13 +6,13 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Undirected graph class based on adjacency list */
|
||||
/* Undirected graph class implemented with an adjacency list */
|
||||
class GraphAdjList {
|
||||
public:
|
||||
// Adjacency list, key: vertex, value: all adjacent vertices of that vertex
|
||||
// Adjacency list: key is a vertex, value is the list of all its neighbors
|
||||
unordered_map<Vertex *, vector<Vertex *>> adjList;
|
||||
|
||||
/* Remove specified node from vector */
|
||||
/* Remove the specified vertex from the vector */
|
||||
void remove(vector<Vertex *> &vec, Vertex *vet) {
|
||||
for (int i = 0; i < vec.size(); i++) {
|
||||
if (vec[i] == vet) {
|
||||
@@ -37,45 +37,45 @@ class GraphAdjList {
|
||||
return adjList.size();
|
||||
}
|
||||
|
||||
/* Add edge */
|
||||
/* Add an edge */
|
||||
void addEdge(Vertex *vet1, Vertex *vet2) {
|
||||
if (!adjList.count(vet1) || !adjList.count(vet2) || vet1 == vet2)
|
||||
throw invalid_argument("Vertex does not exist");
|
||||
throw invalid_argument("Invalid vertex");
|
||||
// Add edge vet1 - vet2
|
||||
adjList[vet1].push_back(vet2);
|
||||
adjList[vet2].push_back(vet1);
|
||||
}
|
||||
|
||||
/* Remove edge */
|
||||
/* Remove an edge */
|
||||
void removeEdge(Vertex *vet1, Vertex *vet2) {
|
||||
if (!adjList.count(vet1) || !adjList.count(vet2) || vet1 == vet2)
|
||||
throw invalid_argument("Vertex does not exist");
|
||||
throw invalid_argument("Invalid vertex");
|
||||
// Remove edge vet1 - vet2
|
||||
remove(adjList[vet1], vet2);
|
||||
remove(adjList[vet2], vet1);
|
||||
}
|
||||
|
||||
/* Add vertex */
|
||||
/* Add a vertex */
|
||||
void addVertex(Vertex *vet) {
|
||||
if (adjList.count(vet))
|
||||
return;
|
||||
// Add a new linked list in the adjacency list
|
||||
// Add a new list to the adjacency list
|
||||
adjList[vet] = vector<Vertex *>();
|
||||
}
|
||||
|
||||
/* Remove vertex */
|
||||
/* Remove a vertex */
|
||||
void removeVertex(Vertex *vet) {
|
||||
if (!adjList.count(vet))
|
||||
throw invalid_argument("Vertex does not exist");
|
||||
// Remove the linked list corresponding to vertex vet in the adjacency list
|
||||
throw invalid_argument("Invalid vertex");
|
||||
// Remove the list corresponding to vertex vet from the adjacency list
|
||||
adjList.erase(vet);
|
||||
// Traverse the linked lists of other vertices and remove all edges containing vet
|
||||
// Traverse the lists of the other vertices and remove all edges incident to vet
|
||||
for (auto &adj : adjList) {
|
||||
remove(adj.second, vet);
|
||||
}
|
||||
}
|
||||
|
||||
/* Print adjacency list */
|
||||
/* Print the adjacency list */
|
||||
void print() {
|
||||
cout << "Adjacency list =" << endl;
|
||||
for (auto &adj : adjList) {
|
||||
@@ -87,4 +87,4 @@ class GraphAdjList {
|
||||
}
|
||||
};
|
||||
|
||||
// See graph_adjacency_list_test.cpp for test cases
|
||||
// See graph_adjacency_list_test.cpp for the test example
|
||||
|
||||
@@ -6,38 +6,38 @@
|
||||
|
||||
#include "./graph_adjacency_list.cpp"
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Add edge */
|
||||
/* Initialize the undirected graph */
|
||||
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, graph is" << endl;
|
||||
cout << "\nGraph after initialization:" << endl;
|
||||
graph.print();
|
||||
|
||||
/* Add edge */
|
||||
// Vertices 1, 3 are v[0], v[1]
|
||||
/* Add an edge */
|
||||
// Vertices 1 and 2 are v[0] and v[2]
|
||||
graph.addEdge(v[0], v[2]);
|
||||
cout << "\nAfter adding edge 1-2, graph is" << endl;
|
||||
cout << "\nGraph after adding edge 1-2:" << endl;
|
||||
graph.print();
|
||||
|
||||
/* Remove edge */
|
||||
// Vertex 3 is v[1]
|
||||
/* Remove an edge */
|
||||
// Vertices 1 and 3 are v[0] and v[1]
|
||||
graph.removeEdge(v[0], v[1]);
|
||||
cout << "\nAfter removing edge 1-3, graph is" << endl;
|
||||
cout << "\nGraph after removing edge 1-3:" << endl;
|
||||
graph.print();
|
||||
|
||||
/* Add vertex */
|
||||
/* Add a vertex */
|
||||
Vertex *v5 = new Vertex(6);
|
||||
graph.addVertex(v5);
|
||||
cout << "\nAfter adding vertex 6, graph is" << endl;
|
||||
cout << "\nGraph after adding vertex 6:" << endl;
|
||||
graph.print();
|
||||
|
||||
/* Remove vertex */
|
||||
/* Remove a vertex */
|
||||
// Vertex 3 is v[1]
|
||||
graph.removeVertex(v[1]);
|
||||
cout << "\nAfter removing vertex 3, graph is" << endl;
|
||||
cout << "\nGraph after removing vertex 3:" << endl;
|
||||
graph.print();
|
||||
|
||||
// Free memory
|
||||
|
||||
@@ -6,20 +6,20 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Undirected graph class based on adjacency matrix */
|
||||
/* Undirected graph class implemented with an adjacency matrix */
|
||||
class GraphAdjMat {
|
||||
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"
|
||||
vector<int> vertices; // Vertex list: elements are vertex values, and indices are vertex indices
|
||||
vector<vector<int>> adjMat; // Adjacency matrix: row and column indices correspond to vertex indices
|
||||
|
||||
public:
|
||||
/* Constructor */
|
||||
GraphAdjMat(const vector<int> &vertices, const vector<vector<int>> &edges) {
|
||||
// Add vertex
|
||||
// Add a vertex
|
||||
for (int val : vertices) {
|
||||
addVertex(val);
|
||||
}
|
||||
// Add edge
|
||||
// Note that the edges elements represent vertex indices, i.e., corresponding to the vertices element indices
|
||||
// Add an edge
|
||||
// Note that the entries in edges are vertex indices, corresponding to element indices in vertices
|
||||
for (const vector<int> &edge : edges) {
|
||||
addEdge(edge[0], edge[1]);
|
||||
}
|
||||
@@ -30,10 +30,10 @@ class GraphAdjMat {
|
||||
return vertices.size();
|
||||
}
|
||||
|
||||
/* Add vertex */
|
||||
/* Add a vertex */
|
||||
void addVertex(int val) {
|
||||
int n = size();
|
||||
// Add the value of the new vertex to the vertex list
|
||||
// Append the new vertex value to the vertex list
|
||||
vertices.push_back(val);
|
||||
// Add a row to the adjacency matrix
|
||||
adjMat.emplace_back(vector<int>(n, 0));
|
||||
@@ -43,45 +43,45 @@ class GraphAdjMat {
|
||||
}
|
||||
}
|
||||
|
||||
/* Remove vertex */
|
||||
/* Remove a vertex */
|
||||
void removeVertex(int index) {
|
||||
if (index >= size()) {
|
||||
throw out_of_range("Vertex does not exist");
|
||||
throw out_of_range("Invalid vertex");
|
||||
}
|
||||
// Remove the vertex at index from the vertex list
|
||||
// Remove the vertex at index `index` from the vertex list
|
||||
vertices.erase(vertices.begin() + index);
|
||||
// Remove the row at index from the adjacency matrix
|
||||
// Remove row `index` from the adjacency matrix
|
||||
adjMat.erase(adjMat.begin() + index);
|
||||
// Remove the column at index from the adjacency matrix
|
||||
// Remove column `index` from the adjacency matrix
|
||||
for (vector<int> &row : adjMat) {
|
||||
row.erase(row.begin() + index);
|
||||
}
|
||||
}
|
||||
|
||||
/* Add edge */
|
||||
// Parameters i, j correspond to the vertices element indices
|
||||
/* Add an edge */
|
||||
// Parameters i and j are element indices in vertices
|
||||
void addEdge(int i, int j) {
|
||||
// Handle index out of bounds and equality
|
||||
// Handle out-of-bounds or equal indices
|
||||
if (i < 0 || j < 0 || i >= size() || j >= size() || i == j) {
|
||||
throw out_of_range("Vertex does not exist");
|
||||
throw out_of_range("Invalid vertex");
|
||||
}
|
||||
// In an undirected graph, the adjacency matrix is symmetric about the main diagonal, i.e., (i, j) == (j, i)
|
||||
// For an undirected graph, the adjacency matrix is symmetric about its main diagonal: entries (i, j) and (j, i) are equal
|
||||
adjMat[i][j] = 1;
|
||||
adjMat[j][i] = 1;
|
||||
}
|
||||
|
||||
/* Remove edge */
|
||||
// Parameters i, j correspond to the vertices element indices
|
||||
/* Remove an edge */
|
||||
// Parameters i and j are element indices in vertices
|
||||
void removeEdge(int i, int j) {
|
||||
// Handle index out of bounds and equality
|
||||
// Handle out-of-bounds or equal indices
|
||||
if (i < 0 || j < 0 || i >= size() || j >= size() || i == j) {
|
||||
throw out_of_range("Vertex does not exist");
|
||||
throw out_of_range("Invalid vertex");
|
||||
}
|
||||
adjMat[i][j] = 0;
|
||||
adjMat[j][i] = 0;
|
||||
}
|
||||
|
||||
/* Print adjacency matrix */
|
||||
/* Print the adjacency matrix */
|
||||
void print() {
|
||||
cout << "Vertex list = ";
|
||||
printVector(vertices);
|
||||
@@ -90,37 +90,37 @@ class GraphAdjMat {
|
||||
}
|
||||
};
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Add edge */
|
||||
// Note that the edges elements represent vertex indices, i.e., corresponding to the vertices element indices
|
||||
/* Initialize the undirected graph */
|
||||
// Note that the entries in edges are vertex indices, corresponding to element indices in vertices
|
||||
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, graph is" << endl;
|
||||
cout << "\nGraph after initialization:" << endl;
|
||||
graph.print();
|
||||
|
||||
/* Add edge */
|
||||
// Add vertex
|
||||
/* Add an edge */
|
||||
// Vertices 1 and 2 have indices 0 and 2, respectively
|
||||
graph.addEdge(0, 2);
|
||||
cout << "\nAfter adding edge 1-2, graph is" << endl;
|
||||
cout << "\nGraph after adding edge 1-2:" << endl;
|
||||
graph.print();
|
||||
|
||||
/* Remove edge */
|
||||
// Vertices 1, 3 have indices 0, 1 respectively
|
||||
/* Remove an edge */
|
||||
// Vertices 1 and 3 have indices 0 and 1, respectively
|
||||
graph.removeEdge(0, 1);
|
||||
cout << "\nAfter removing edge 1-3, graph is" << endl;
|
||||
cout << "\nGraph after removing edge 1-3:" << endl;
|
||||
graph.print();
|
||||
|
||||
/* Add vertex */
|
||||
/* Add a vertex */
|
||||
graph.addVertex(6);
|
||||
cout << "\nAfter adding vertex 6, graph is" << endl;
|
||||
cout << "\nGraph after adding vertex 6:" << endl;
|
||||
graph.print();
|
||||
|
||||
/* Remove vertex */
|
||||
/* Remove a vertex */
|
||||
// Vertex 3 has index 1
|
||||
graph.removeVertex(1);
|
||||
cout << "\nAfter removing vertex 3, graph is" << endl;
|
||||
cout << "\nGraph after removing vertex 3:" << endl;
|
||||
graph.print();
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -8,46 +8,46 @@
|
||||
#include "./graph_adjacency_list.cpp"
|
||||
|
||||
/* Breadth-first traversal */
|
||||
// Use adjacency list to represent the graph, in order to obtain all adjacent vertices of a specified vertex
|
||||
// Represent the graph with an adjacency list to access all neighbors of a given vertex
|
||||
vector<Vertex *> graphBFS(GraphAdjList &graph, Vertex *startVet) {
|
||||
// Vertex traversal sequence
|
||||
vector<Vertex *> res;
|
||||
// Hash set for recording vertices that have been visited
|
||||
// Hash set recording visited vertices
|
||||
unordered_set<Vertex *> visited = {startVet};
|
||||
// Queue used to implement BFS
|
||||
// Use a queue to implement BFS
|
||||
queue<Vertex *> que;
|
||||
que.push(startVet);
|
||||
// Starting from vertex vet, loop until all vertices are visited
|
||||
// Starting from startVet, continue until all reachable vertices have been visited
|
||||
while (!que.empty()) {
|
||||
Vertex *vet = que.front();
|
||||
que.pop(); // Dequeue the front vertex
|
||||
res.push_back(vet); // Record visited vertex
|
||||
// Traverse all adjacent vertices of this vertex
|
||||
res.push_back(vet); // Record the visited vertex
|
||||
// Traverse all neighbors of this vertex
|
||||
for (auto adjVet : graph.adjList[vet]) {
|
||||
if (visited.count(adjVet))
|
||||
continue; // Skip vertices that have been visited
|
||||
que.push(adjVet); // Only enqueue unvisited vertices
|
||||
continue; // Skip vertices that have already been visited
|
||||
que.push(adjVet); // Enqueue only unvisited vertices
|
||||
visited.emplace(adjVet); // Mark this vertex as visited
|
||||
}
|
||||
}
|
||||
// Return vertex traversal sequence
|
||||
// Return the vertex traversal sequence
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Add edge */
|
||||
/* Initialize the undirected graph */
|
||||
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, graph is\\n";
|
||||
cout << "\nGraph after initialization:\\n";
|
||||
graph.print();
|
||||
|
||||
/* Breadth-first traversal */
|
||||
vector<Vertex *> res = graphBFS(graph, v[0]);
|
||||
cout << "\nBreadth-first traversal (BFS) vertex sequence is" << endl;
|
||||
cout << "\nVertex sequence from breadth-first traversal (BFS):" << endl;
|
||||
printVector(vetsToVals(res));
|
||||
|
||||
// Free memory
|
||||
|
||||
@@ -9,41 +9,41 @@
|
||||
|
||||
/* 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
|
||||
res.push_back(vet); // Record the visited vertex
|
||||
visited.emplace(vet); // Mark this vertex as visited
|
||||
// Traverse all adjacent vertices of this vertex
|
||||
// Traverse all neighbors of this vertex
|
||||
for (Vertex *adjVet : graph.adjList[vet]) {
|
||||
if (visited.count(adjVet))
|
||||
continue; // Skip vertices that have been visited
|
||||
// Recursively visit adjacent vertices
|
||||
continue; // Skip vertices that have already been visited
|
||||
// Recursively visit the neighboring vertex
|
||||
dfs(graph, visited, res, adjVet);
|
||||
}
|
||||
}
|
||||
|
||||
/* Depth-first traversal */
|
||||
// Use adjacency list to represent the graph, in order to obtain all adjacent vertices of a specified vertex
|
||||
// Represent the graph with an adjacency list to access all neighbors of a given vertex
|
||||
vector<Vertex *> graphDFS(GraphAdjList &graph, Vertex *startVet) {
|
||||
// Vertex traversal sequence
|
||||
vector<Vertex *> res;
|
||||
// Hash set for recording vertices that have been visited
|
||||
// Hash set recording visited vertices
|
||||
unordered_set<Vertex *> visited;
|
||||
dfs(graph, visited, res, startVet);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Add edge */
|
||||
/* Initialize the undirected graph */
|
||||
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, graph is" << endl;
|
||||
cout << "\nGraph after initialization:" << endl;
|
||||
graph.print();
|
||||
|
||||
/* Depth-first traversal */
|
||||
vector<Vertex *> res = graphDFS(graph, v[0]);
|
||||
cout << "\nDepth-first traversal (DFS) vertex sequence is" << endl;
|
||||
cout << "\nVertex sequence from depth-first traversal (DFS):" << endl;
|
||||
printVector(vetsToVals(res));
|
||||
|
||||
// Free memory
|
||||
|
||||
@@ -6,14 +6,14 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Coin change: Greedy algorithm */
|
||||
/* Coin change: greedy algorithm */
|
||||
int coinChangeGreedy(vector<int> &coins, int amt) {
|
||||
// Assume coins list is sorted
|
||||
// Assume the coins list is sorted
|
||||
int i = coins.size() - 1;
|
||||
int count = 0;
|
||||
// Loop to make greedy choices until no remaining amount
|
||||
// Repeatedly make greedy choices until no amount remains
|
||||
while (amt > 0) {
|
||||
// Find the coin that is less than and closest to the remaining amount
|
||||
// Find the largest coin that does not exceed the remaining amount
|
||||
while (i > 0 && coins[i] > amt) {
|
||||
i--;
|
||||
}
|
||||
@@ -21,40 +21,40 @@ int coinChangeGreedy(vector<int> &coins, int amt) {
|
||||
amt -= coins[i];
|
||||
count++;
|
||||
}
|
||||
// If no feasible solution is found, return -1
|
||||
// Return -1 if no feasible solution was found
|
||||
return amt == 0 ? count : -1;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
// Greedy algorithm: Can guarantee finding the global optimal solution
|
||||
// Greedy algorithm: guaranteed to find a globally 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 << "Minimum number of coins needed to make " << amt << " is " << res << endl;
|
||||
cout << "For amount " << amt << " , the greedy coin count is " << res << endl;
|
||||
|
||||
// Greedy algorithm: Cannot guarantee finding the global optimal solution
|
||||
// Greedy algorithm: not guaranteed to find a globally optimal solution
|
||||
coins = {1, 20, 50};
|
||||
amt = 60;
|
||||
res = coinChangeGreedy(coins, amt);
|
||||
cout << "\ncoins = ";
|
||||
printVector(coins);
|
||||
cout << "amt = " << amt << 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;
|
||||
cout << "For amount " << amt << " , the greedy coin count is " << res << endl;
|
||||
cout << "The actual minimum is 3 coins: 20 + 20 + 20" << endl;
|
||||
|
||||
// Greedy algorithm: Cannot guarantee finding the global optimal solution
|
||||
// Greedy algorithm: not guaranteed to find a globally optimal solution
|
||||
coins = {1, 49, 50};
|
||||
amt = 98;
|
||||
res = coinChangeGreedy(coins, amt);
|
||||
cout << "\ncoins = ";
|
||||
printVector(coins);
|
||||
cout << "amt = " << amt << 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;
|
||||
cout << "For amount " << amt << " , the greedy coin count is " << res << endl;
|
||||
cout << "The actual minimum is 2 coins: 49 + 49" << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -16,33 +16,33 @@ class Item {
|
||||
}
|
||||
};
|
||||
|
||||
/* Fractional knapsack: Greedy algorithm */
|
||||
/* Fractional knapsack: greedy algorithm */
|
||||
double fractionalKnapsack(vector<int> &wgt, vector<int> &val, int cap) {
|
||||
// Create item list with two attributes: weight, value
|
||||
// Create a list of items, each with two attributes: weight and value
|
||||
vector<Item> items;
|
||||
for (int i = 0; i < wgt.size(); i++) {
|
||||
items.push_back(Item(wgt[i], val[i]));
|
||||
}
|
||||
// Sort by unit value item.v / item.w from high to low
|
||||
// Sort by value per unit weight, item.v / item.w, in descending order
|
||||
sort(items.begin(), items.end(), [](Item &a, Item &b) { return (double)a.v / a.w > (double)b.v / b.w; });
|
||||
// Loop for greedy selection
|
||||
// Repeatedly make greedy choices
|
||||
double res = 0;
|
||||
for (auto &item : items) {
|
||||
if (item.w <= cap) {
|
||||
// If remaining capacity is sufficient, put the entire current item into the knapsack
|
||||
// If enough capacity remains, put the entire current item in the knapsack
|
||||
res += item.v;
|
||||
cap -= item.w;
|
||||
} else {
|
||||
// If remaining capacity is insufficient, put part of the current item into the knapsack
|
||||
// If the remaining capacity is insufficient, put part of the current item in the knapsack
|
||||
res += (double)item.v / item.w * cap;
|
||||
// No remaining capacity, so break out of the loop
|
||||
// No capacity remains, so exit the loop
|
||||
break;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
vector<int> wgt = {10, 20, 30, 40, 50};
|
||||
vector<int> val = {50, 120, 150, 210, 240};
|
||||
@@ -50,7 +50,7 @@ int main() {
|
||||
|
||||
// Greedy algorithm
|
||||
double res = fractionalKnapsack(wgt, val, cap);
|
||||
cout << "Maximum item value not exceeding knapsack capacity is " << res << endl;
|
||||
cout << "Maximum total item value within the knapsack capacity: " << res << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -6,18 +6,18 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Max capacity: Greedy algorithm */
|
||||
/* Maximum container capacity: greedy algorithm */
|
||||
int maxCapacity(vector<int> &ht) {
|
||||
// Initialize i, j to be at both ends of the array
|
||||
// Initialize i and j at opposite ends of the array
|
||||
int i = 0, j = ht.size() - 1;
|
||||
// Initial max capacity is 0
|
||||
// The initial maximum capacity is 0
|
||||
int res = 0;
|
||||
// Loop for greedy selection until the two boards meet
|
||||
// Repeatedly make greedy choices until the two sides meet
|
||||
while (i < j) {
|
||||
// Update max capacity
|
||||
// Update the maximum capacity
|
||||
int cap = min(ht[i], ht[j]) * (j - i);
|
||||
res = max(res, cap);
|
||||
// Move the shorter board inward
|
||||
// Move the shorter side inward
|
||||
if (ht[i] < ht[j]) {
|
||||
i++;
|
||||
} else {
|
||||
@@ -27,13 +27,13 @@ int maxCapacity(vector<int> &ht) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
vector<int> ht = {3, 8, 5, 2, 7, 7, 3, 4};
|
||||
|
||||
// Greedy algorithm
|
||||
int res = maxCapacity(ht);
|
||||
cout << "Maximum capacity is " << res << endl;
|
||||
cout << "Maximum capacity: " << res << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -6,34 +6,34 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Max product cutting: Greedy algorithm */
|
||||
/* Maximum product after splitting: greedy algorithm */
|
||||
int maxProductCutting(int n) {
|
||||
// When n <= 3, must cut out a 1
|
||||
// When n <= 3, one part must be 1
|
||||
if (n <= 3) {
|
||||
return 1 * (n - 1);
|
||||
}
|
||||
// Greedily cut out 3, a is the number of 3s, b is the remainder
|
||||
// Greedily split off parts of size 3; a is the number of 3s and 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 to 2 * 2
|
||||
// When the remainder is 1, replace one pair 1 * 3 with 2 * 2
|
||||
return (int)pow(3, a - 1) * 2 * 2;
|
||||
}
|
||||
if (b == 2) {
|
||||
// When the remainder is 2, do nothing
|
||||
// When the remainder is 2, no adjustment is needed
|
||||
return (int)pow(3, a) * 2;
|
||||
}
|
||||
// When the remainder is 0, do nothing
|
||||
// When the remainder is 0, no adjustment is needed
|
||||
return (int)pow(3, a);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int n = 58;
|
||||
|
||||
// Greedy algorithm
|
||||
int res = maxProductCutting(n);
|
||||
cout << "Maximum cutting product is" << res << endl;
|
||||
cout << "Maximum product after cutting: " << res << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -17,14 +17,14 @@ struct Pair {
|
||||
}
|
||||
};
|
||||
|
||||
/* Hash table based on array implementation */
|
||||
/* Hash table implemented with an array */
|
||||
class ArrayHashMap {
|
||||
private:
|
||||
vector<Pair *> buckets;
|
||||
|
||||
public:
|
||||
ArrayHashMap() {
|
||||
// Initialize array with 100 buckets
|
||||
// Initialize an array containing 100 buckets
|
||||
buckets = vector<Pair *>(100);
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ class ArrayHashMap {
|
||||
return index;
|
||||
}
|
||||
|
||||
/* Query operation */
|
||||
/* Lookup operation */
|
||||
string get(int key) {
|
||||
int index = hashFunc(key);
|
||||
Pair *pair = buckets[index];
|
||||
@@ -51,7 +51,7 @@ class ArrayHashMap {
|
||||
return pair->val;
|
||||
}
|
||||
|
||||
/* Add operation */
|
||||
/* Insert operation */
|
||||
void put(int key, string val) {
|
||||
Pair *pair = new Pair(key, val);
|
||||
int index = hashFunc(key);
|
||||
@@ -61,7 +61,7 @@ class ArrayHashMap {
|
||||
/* Remove operation */
|
||||
void remove(int key) {
|
||||
int index = hashFunc(key);
|
||||
// Free memory and set to nullptr
|
||||
// Free the memory and set the pointer to nullptr
|
||||
delete buckets[index];
|
||||
buckets[index] = nullptr;
|
||||
}
|
||||
@@ -99,7 +99,7 @@ class ArrayHashMap {
|
||||
return valueSet;
|
||||
}
|
||||
|
||||
/* Print hash table */
|
||||
/* Print the hash table */
|
||||
void print() {
|
||||
for (Pair *kv : pairSet()) {
|
||||
cout << kv->key << " -> " << kv->val << endl;
|
||||
@@ -107,4 +107,4 @@ class ArrayHashMap {
|
||||
}
|
||||
};
|
||||
|
||||
// See array_hash_map_test.cpp for test cases
|
||||
// See array_hash_map_test.cpp for the test example
|
||||
|
||||
@@ -6,44 +6,44 @@
|
||||
|
||||
#include "./array_hash_map.cpp"
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Initialize hash table */
|
||||
/* Initialize the hash table */
|
||||
ArrayHashMap map = ArrayHashMap();
|
||||
|
||||
/* Add operation */
|
||||
// Add key-value pair (key, value) to the hash table
|
||||
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;
|
||||
/* Insert operation */
|
||||
// Insert the key-value pair (key, value) into the hash table
|
||||
map.put(12836, "小哈");
|
||||
map.put(15937, "小啰");
|
||||
map.put(16750, "小算");
|
||||
map.put(13276, "小法");
|
||||
map.put(10583, "小鸭");
|
||||
cout << "\nHash table after insertion:\nKey -> Value" << endl;
|
||||
map.print();
|
||||
|
||||
/* Query operation */
|
||||
// Input key into hash table to get value
|
||||
/* Lookup operation */
|
||||
// Look up key in the hash table to obtain value
|
||||
string name = map.get(15937);
|
||||
cout << "\nInput student ID 15937, query name " << name << endl;
|
||||
cout << "\nLook up student ID 15937 to obtain the name " << name << endl;
|
||||
|
||||
/* Remove operation */
|
||||
// Remove key-value pair (key, value) from hash table
|
||||
// Remove the key-value pair (key, value) from the hash table
|
||||
map.remove(10583);
|
||||
cout << "\nAfter removing 10583, hash table is\nKey -> Value" << endl;
|
||||
cout << "\nHash table after removing 10583:\nKey -> Value" << endl;
|
||||
map.print();
|
||||
|
||||
/* Traverse hash table */
|
||||
cout << "\nTraverse key-value pairs Key->Value" << endl;
|
||||
/* Traverse the hash table */
|
||||
cout << "\nTraverse key-value pairs: Key->Value" << endl;
|
||||
for (auto kv : map.pairSet()) {
|
||||
cout << kv->key << " -> " << kv->val << endl;
|
||||
}
|
||||
|
||||
cout << "\nTraverse keys only Key" << endl;
|
||||
cout << "\nTraverse keys only: Key" << endl;
|
||||
for (auto key : map.keySet()) {
|
||||
cout << key << endl;
|
||||
}
|
||||
|
||||
cout << "\nTraverse values only Value" << endl;
|
||||
cout << "\nTraverse values only: Value" << endl;
|
||||
for (auto val : map.valueSet()) {
|
||||
cout << val << endl;
|
||||
}
|
||||
|
||||
@@ -6,24 +6,24 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int num = 3;
|
||||
size_t hashNum = hash<int>()(num);
|
||||
cout << "Hash value of integer " << num << " is " << hashNum << "\n";
|
||||
cout << "Integer " << num << " has hash value " << hashNum << "\n";
|
||||
|
||||
bool bol = true;
|
||||
size_t hashBol = hash<bool>()(bol);
|
||||
cout << "Hash value of boolean " << bol << " is " << hashBol << "\n";
|
||||
cout << "Boolean " << bol << " has hash value " << hashBol << "\n";
|
||||
|
||||
double dec = 3.14159;
|
||||
size_t hashDec = hash<double>()(dec);
|
||||
cout << "Hash value of decimal " << dec << " is " << hashDec << "\n";
|
||||
cout << "Floating-point number " << dec << " has hash value " << hashDec << "\n";
|
||||
|
||||
string str = "Hello Algo";
|
||||
string str = "Hello 算法";
|
||||
size_t hashStr = hash<string>()(str);
|
||||
cout << "Hash value of string " << str << " is " << hashStr << "\n";
|
||||
cout << "String " << str << " has hash value " << hashStr << "\n";
|
||||
|
||||
// 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
|
||||
// C++ std::hash provides hashing for fundamental types and selected standard-library types
|
||||
// For arrays and unsupported object types, supply your own hash implementation
|
||||
}
|
||||
|
||||
@@ -6,38 +6,38 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Initialize hash table */
|
||||
/* Initialize the hash table */
|
||||
unordered_map<int, string> map;
|
||||
|
||||
/* Add operation */
|
||||
// Add key-value pair (key, value) to the hash table
|
||||
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;
|
||||
/* Insert operation */
|
||||
// Insert the key-value pair (key, value) into the hash table
|
||||
map[12836] = "小哈";
|
||||
map[15937] = "小啰";
|
||||
map[16750] = "小算";
|
||||
map[13276] = "小法";
|
||||
map[10583] = "小鸭";
|
||||
cout << "\nHash table after insertion:\nKey -> Value" << endl;
|
||||
printHashMap(map);
|
||||
|
||||
/* Query operation */
|
||||
// Input key into hash table to get value
|
||||
/* Lookup operation */
|
||||
// Look up key in the hash table to obtain value
|
||||
string name = map[15937];
|
||||
cout << "\nInput student ID 15937, query name " << name << endl;
|
||||
cout << "\nLook up student ID 15937 to obtain the name " << name << endl;
|
||||
|
||||
/* Remove operation */
|
||||
// Remove key-value pair (key, value) from hash table
|
||||
// Remove the key-value pair (key, value) from the hash table
|
||||
map.erase(10583);
|
||||
cout << "\nAfter removing 10583, hash table is\nKey -> Value" << endl;
|
||||
cout << "\nHash table after removing 10583:\nKey -> Value" << endl;
|
||||
printHashMap(map);
|
||||
|
||||
/* Traverse hash table */
|
||||
cout << "\nTraverse key-value pairs Key->Value" << endl;
|
||||
/* Traverse the hash table */
|
||||
cout << "\nTraverse key-value pairs: Key->Value" << endl;
|
||||
for (auto kv : map) {
|
||||
cout << kv.first << " -> " << kv.second << endl;
|
||||
}
|
||||
cout << "\nTraverse Key->Value using iterator" << endl;
|
||||
cout << "\nTraverse Key->Value pairs using an iterator" << endl;
|
||||
for (auto iter = map.begin(); iter != map.end(); iter++) {
|
||||
cout << iter->first << "->" << iter->second << endl;
|
||||
}
|
||||
|
||||
@@ -11,8 +11,8 @@ class HashMapChaining {
|
||||
private:
|
||||
int size; // Number of key-value pairs
|
||||
int capacity; // Hash table capacity
|
||||
double loadThres; // Load factor threshold for triggering expansion
|
||||
int extendRatio; // Expansion multiplier
|
||||
double loadThres; // Load factor threshold that triggers capacity growth
|
||||
int extendRatio; // Capacity growth factor
|
||||
vector<vector<Pair *>> buckets; // Bucket array
|
||||
|
||||
public:
|
||||
@@ -41,34 +41,34 @@ class HashMapChaining {
|
||||
return (double)size / (double)capacity;
|
||||
}
|
||||
|
||||
/* Query operation */
|
||||
/* Lookup operation */
|
||||
string get(int key) {
|
||||
int index = hashFunc(key);
|
||||
// Traverse bucket, if key is found, return corresponding val
|
||||
// Traverse the bucket; if key is found, return its corresponding val
|
||||
for (Pair *pair : buckets[index]) {
|
||||
if (pair->key == key) {
|
||||
return pair->val;
|
||||
}
|
||||
}
|
||||
// Return empty string if key not found
|
||||
// Return an empty string if key is not found
|
||||
return "";
|
||||
}
|
||||
|
||||
/* Add operation */
|
||||
/* Insert operation */
|
||||
void put(int key, string val) {
|
||||
// When load factor exceeds threshold, perform expansion
|
||||
// Grow the capacity when the load factor exceeds the threshold
|
||||
if (loadFactor() > loadThres) {
|
||||
extend();
|
||||
}
|
||||
int index = hashFunc(key);
|
||||
// Traverse bucket, if specified key is encountered, update corresponding val and return
|
||||
// Traverse the bucket; if the specified key is found, update its val and return
|
||||
for (Pair *pair : buckets[index]) {
|
||||
if (pair->key == key) {
|
||||
pair->val = val;
|
||||
return;
|
||||
}
|
||||
}
|
||||
// If key does not exist, append key-value pair to the end
|
||||
// If key is absent, append the key-value pair at 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 bucket and remove key-value pair from it
|
||||
// Traverse the bucket and remove the key-value pair
|
||||
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 from it
|
||||
bucket.erase(bucket.begin() + i); // Remove the key-value pair from the list
|
||||
delete tmp; // Free memory
|
||||
size--;
|
||||
return;
|
||||
@@ -89,16 +89,16 @@ class HashMapChaining {
|
||||
}
|
||||
}
|
||||
|
||||
/* Expand hash table */
|
||||
/* Grow the hash table capacity */
|
||||
void extend() {
|
||||
// Temporarily store the original hash table
|
||||
// Keep a copy of the original bucket array
|
||||
vector<vector<Pair *>> bucketsTmp = buckets;
|
||||
// Initialize expanded new hash table
|
||||
// Initialize a new hash table with the expanded capacity
|
||||
capacity *= extendRatio;
|
||||
buckets.clear();
|
||||
buckets.resize(capacity);
|
||||
size = 0;
|
||||
// Move key-value pairs from original hash table to new hash table
|
||||
// Move the key-value pairs from the original hash table to the new one
|
||||
for (auto &bucket : bucketsTmp) {
|
||||
for (Pair *pair : bucket) {
|
||||
put(pair->key, pair->val);
|
||||
@@ -108,7 +108,7 @@ class HashMapChaining {
|
||||
}
|
||||
}
|
||||
|
||||
/* Print hash table */
|
||||
/* Print the hash table */
|
||||
void print() {
|
||||
for (auto &bucket : buckets) {
|
||||
cout << "[";
|
||||
@@ -120,30 +120,30 @@ class HashMapChaining {
|
||||
}
|
||||
};
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Initialize hash table */
|
||||
/* Initialize the hash table */
|
||||
HashMapChaining map = HashMapChaining();
|
||||
|
||||
/* Add operation */
|
||||
// Add key-value pair (key, value) to the hash table
|
||||
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;
|
||||
/* Insert operation */
|
||||
// Insert the key-value pair (key, value) into the hash table
|
||||
map.put(12836, "小哈");
|
||||
map.put(15937, "小啰");
|
||||
map.put(16750, "小算");
|
||||
map.put(13276, "小法");
|
||||
map.put(10583, "小鸭");
|
||||
cout << "\nHash table after insertion:\nKey -> Value" << endl;
|
||||
map.print();
|
||||
|
||||
/* Query operation */
|
||||
// Input key into hash table to get value
|
||||
/* Lookup operation */
|
||||
// Look up key in the hash table to obtain value
|
||||
string name = map.get(13276);
|
||||
cout << "\nInput student ID 13276, query name " << name << endl;
|
||||
cout << "\nLook up student ID 13276 to obtain the name " << name << endl;
|
||||
|
||||
/* Remove operation */
|
||||
// Remove key-value pair (key, value) from hash table
|
||||
// Remove the key-value pair (key, value) from the hash table
|
||||
map.remove(12836);
|
||||
cout << "\nAfter removing 12836, hash table is\nKey -> Value" << endl;
|
||||
cout << "\nHash table after removing 12836:\nKey -> Value" << endl;
|
||||
map.print();
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -11,10 +11,10 @@ class HashMapOpenAddressing {
|
||||
private:
|
||||
int size; // Number of key-value pairs
|
||||
int capacity = 4; // Hash table capacity
|
||||
const double loadThres = 2.0 / 3.0; // Load factor threshold for triggering expansion
|
||||
const int extendRatio = 2; // Expansion multiplier
|
||||
const double loadThres = 2.0 / 3.0; // Load factor threshold that triggers capacity growth
|
||||
const int extendRatio = 2; // Capacity growth factor
|
||||
vector<Pair *> buckets; // Bucket array
|
||||
Pair *TOMBSTONE = new Pair(-1, "-1"); // Removal marker
|
||||
Pair *TOMBSTONE = new Pair(-1, "-1"); // Tombstone marker
|
||||
|
||||
public:
|
||||
/* Constructor */
|
||||
@@ -41,68 +41,68 @@ class HashMapOpenAddressing {
|
||||
return (double)size / capacity;
|
||||
}
|
||||
|
||||
/* Search for bucket index corresponding to key */
|
||||
/* Find the bucket index for key */
|
||||
int findBucket(int key) {
|
||||
int index = hashFunc(key);
|
||||
int firstTombstone = -1;
|
||||
// Linear probing, break when encountering an empty bucket
|
||||
// Probe linearly until an empty bucket is reached
|
||||
while (buckets[index] != nullptr) {
|
||||
// If key is encountered, return the corresponding bucket index
|
||||
// If key is found, return its bucket index
|
||||
if (buckets[index]->key == key) {
|
||||
// If a removal marker was encountered before, move the key-value pair to that index
|
||||
// If a tombstone was encountered earlier, move the key-value pair to that index
|
||||
if (firstTombstone != -1) {
|
||||
buckets[firstTombstone] = buckets[index];
|
||||
buckets[index] = TOMBSTONE;
|
||||
return firstTombstone; // Return the moved bucket index
|
||||
return firstTombstone; // Return the bucket index after the move
|
||||
}
|
||||
return index; // Return bucket index
|
||||
return index; // Return the bucket index
|
||||
}
|
||||
// Record the first removal marker encountered
|
||||
// Record the first tombstone encountered
|
||||
if (firstTombstone == -1 && buckets[index] == TOMBSTONE) {
|
||||
firstTombstone = index;
|
||||
}
|
||||
// Calculate bucket index, wrap around to the head if past the tail
|
||||
// Calculate the bucket index, wrapping to the beginning after the end
|
||||
index = (index + 1) % capacity;
|
||||
}
|
||||
// If key does not exist, return the index for insertion
|
||||
// If key is absent, return the index for insertion
|
||||
return firstTombstone == -1 ? index : firstTombstone;
|
||||
}
|
||||
|
||||
/* Query operation */
|
||||
/* Lookup operation */
|
||||
string get(int key) {
|
||||
// Search for bucket index corresponding to key
|
||||
// Find the bucket index for key
|
||||
int index = findBucket(key);
|
||||
// If key-value pair is found, return corresponding val
|
||||
// If the key-value pair is found, return its val
|
||||
if (buckets[index] != nullptr && buckets[index] != TOMBSTONE) {
|
||||
return buckets[index]->val;
|
||||
}
|
||||
// Return empty string if key-value pair does not exist
|
||||
// Return an empty string if the key-value pair does not exist
|
||||
return "";
|
||||
}
|
||||
|
||||
/* Add operation */
|
||||
/* Insert operation */
|
||||
void put(int key, string val) {
|
||||
// When load factor exceeds threshold, perform expansion
|
||||
// Grow the capacity when the load factor exceeds the threshold
|
||||
if (loadFactor() > loadThres) {
|
||||
extend();
|
||||
}
|
||||
// Search for bucket index corresponding to key
|
||||
// Find the bucket index for key
|
||||
int index = findBucket(key);
|
||||
// If key-value pair is found, overwrite val and return
|
||||
// If the key-value pair is found, overwrite val and return
|
||||
if (buckets[index] != nullptr && buckets[index] != TOMBSTONE) {
|
||||
buckets[index]->val = val;
|
||||
return;
|
||||
}
|
||||
// If key-value pair does not exist, add the key-value pair
|
||||
// If the key-value pair is absent, insert it
|
||||
buckets[index] = new Pair(key, val);
|
||||
size++;
|
||||
}
|
||||
|
||||
/* Remove operation */
|
||||
void remove(int key) {
|
||||
// Search for bucket index corresponding to key
|
||||
// Find the bucket index for key
|
||||
int index = findBucket(key);
|
||||
// If key-value pair is found, overwrite it with removal marker
|
||||
// If the key-value pair is found, replace it with a tombstone
|
||||
if (buckets[index] != nullptr && buckets[index] != TOMBSTONE) {
|
||||
delete buckets[index];
|
||||
buckets[index] = TOMBSTONE;
|
||||
@@ -110,15 +110,15 @@ class HashMapOpenAddressing {
|
||||
}
|
||||
}
|
||||
|
||||
/* Expand hash table */
|
||||
/* Grow the hash table capacity */
|
||||
void extend() {
|
||||
// Temporarily store the original hash table
|
||||
// Keep a copy of the original bucket array
|
||||
vector<Pair *> bucketsTmp = buckets;
|
||||
// Initialize expanded new hash table
|
||||
// Initialize a new hash table with the expanded capacity
|
||||
capacity *= extendRatio;
|
||||
buckets = vector<Pair *>(capacity, nullptr);
|
||||
size = 0;
|
||||
// Move key-value pairs from original hash table to new hash table
|
||||
// Move the key-value pairs from the original hash table to the new one
|
||||
for (Pair *pair : bucketsTmp) {
|
||||
if (pair != nullptr && pair != TOMBSTONE) {
|
||||
put(pair->key, pair->val);
|
||||
@@ -127,7 +127,7 @@ class HashMapOpenAddressing {
|
||||
}
|
||||
}
|
||||
|
||||
/* Print hash table */
|
||||
/* Print the hash table */
|
||||
void print() {
|
||||
for (Pair *pair : buckets) {
|
||||
if (pair == nullptr) {
|
||||
@@ -141,30 +141,30 @@ class HashMapOpenAddressing {
|
||||
}
|
||||
};
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
// Initialize hash table
|
||||
// Initialize the hash table
|
||||
HashMapOpenAddressing hashmap;
|
||||
|
||||
// Add operation
|
||||
// Add key-value pair (key, val) to the hash table
|
||||
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;
|
||||
// Insert operation
|
||||
// Insert the key-value pair (key, val) into the hash table
|
||||
hashmap.put(12836, "小哈");
|
||||
hashmap.put(15937, "小啰");
|
||||
hashmap.put(16750, "小算");
|
||||
hashmap.put(13276, "小法");
|
||||
hashmap.put(10583, "小鸭");
|
||||
cout << "\nHash table after insertion:\nKey -> Value" << endl;
|
||||
hashmap.print();
|
||||
|
||||
// Query operation
|
||||
// Input key into hash table to get value val
|
||||
// Lookup operation
|
||||
// Look up key in the hash table to obtain val
|
||||
string name = hashmap.get(13276);
|
||||
cout << "\nInput student ID 13276, query name " << name << endl;
|
||||
cout << "\nLook up student ID 13276 to obtain the name " << name << endl;
|
||||
|
||||
// Remove operation
|
||||
// Remove key-value pair (key, val) from hash table
|
||||
// Remove the key-value pair (key, val) from the hash table
|
||||
hashmap.remove(16750);
|
||||
cout << "\nAfter removing 16750, hash table is\nKey -> Value" << endl;
|
||||
cout << "\nHash table after removing 16750:\nKey -> Value" << endl;
|
||||
hashmap.print();
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -36,7 +36,7 @@ int xorHash(string key) {
|
||||
return hash & MODULUS;
|
||||
}
|
||||
|
||||
/* Rotational hash */
|
||||
/* Rotating hash */
|
||||
int rotHash(string key) {
|
||||
long long hash = 0;
|
||||
const int MODULUS = 1000000007;
|
||||
@@ -46,21 +46,21 @@ int rotHash(string key) {
|
||||
return (int)hash;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
string key = "Hello Algo";
|
||||
string key = "Hello 算法";
|
||||
|
||||
int hash = addHash(key);
|
||||
cout << "Additive hash value is " << hash << endl;
|
||||
cout << "Additive hash value: " << hash << endl;
|
||||
|
||||
hash = mulHash(key);
|
||||
cout << "Multiplicative hash value is " << hash << endl;
|
||||
cout << "Multiplicative hash value: " << hash << endl;
|
||||
|
||||
hash = xorHash(key);
|
||||
cout << "XOR hash value is " << hash << endl;
|
||||
cout << "XOR hash value: " << hash << endl;
|
||||
|
||||
hash = rotHash(key);
|
||||
cout << "Rotational hash value is " << hash << endl;
|
||||
cout << "Rotation hash value: " << hash << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -7,59 +7,59 @@
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
void testPush(priority_queue<int> &heap, int val) {
|
||||
heap.push(val); // Element enters heap
|
||||
cout << "\nAfter element " << val << " pushes to heap" << endl;
|
||||
heap.push(val); // Push an element onto the heap
|
||||
cout << "\nAfter pushing element " << val << " onto the heap:" << endl;
|
||||
printHeap(heap);
|
||||
}
|
||||
|
||||
void testPop(priority_queue<int> &heap) {
|
||||
int val = heap.top();
|
||||
heap.pop();
|
||||
cout << "\nAfter heap top element " << val << " pops from heap" << endl;
|
||||
cout << "\nAfter popping top element " << val << " from the heap:" << endl;
|
||||
printHeap(heap);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Initialize heap */
|
||||
// Python's heapq module implements min heap by default
|
||||
/* Initialize the heap */
|
||||
// Initialize a min heap
|
||||
// priority_queue<int, vector<int>, greater<int>> minHeap;
|
||||
// Consider negating the elements before entering the heap, which can reverse the size relationship, thus implementing max heap
|
||||
// Initialize a max heap
|
||||
priority_queue<int, vector<int>, less<int>> maxHeap;
|
||||
|
||||
cout << "\nThe following test cases are for max heap" << endl;
|
||||
cout << "\nThe following example uses a max heap" << endl;
|
||||
|
||||
/* Element enters heap */
|
||||
/* Push an element onto the heap */
|
||||
testPush(maxHeap, 1);
|
||||
testPush(maxHeap, 3);
|
||||
testPush(maxHeap, 2);
|
||||
testPush(maxHeap, 5);
|
||||
testPush(maxHeap, 4);
|
||||
|
||||
/* Check if heap is empty */
|
||||
/* Get the top element of the heap */
|
||||
int peek = maxHeap.top();
|
||||
cout << "\nHeap top element is " << peek << endl;
|
||||
cout << "\nTop element of the heap: " << peek << endl;
|
||||
|
||||
/* Time complexity is O(n), not O(nlogn) */
|
||||
/* Pop the top element from the heap */
|
||||
testPop(maxHeap);
|
||||
testPop(maxHeap);
|
||||
testPop(maxHeap);
|
||||
testPop(maxHeap);
|
||||
testPop(maxHeap);
|
||||
|
||||
/* Get heap size */
|
||||
/* Get the heap size */
|
||||
int size = maxHeap.size();
|
||||
cout << "\nHeap size is " << size << endl;
|
||||
cout << "\nNumber of elements in the heap: " << size << endl;
|
||||
|
||||
/* Check if heap is empty */
|
||||
/* Check whether the heap is empty */
|
||||
bool isEmpty = maxHeap.empty();
|
||||
cout << "\nIs heap empty " << isEmpty << endl;
|
||||
cout << "\nIs the heap empty: " << isEmpty << endl;
|
||||
|
||||
/* Input list and build heap */
|
||||
// Time complexity is O(n), not O(nlogn)
|
||||
/* Build a heap from an input list */
|
||||
// The 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 input list and building min heap" << endl;
|
||||
cout << "After building a min heap from the input list:" << endl;
|
||||
printHeap(minHeap);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -9,147 +9,147 @@
|
||||
/* Max heap */
|
||||
class MaxHeap {
|
||||
private:
|
||||
// Use dynamic array to avoid expansion issues
|
||||
// Use a dynamic array so capacity growth is handled automatically
|
||||
vector<int> maxHeap;
|
||||
|
||||
/* Get index of left child node */
|
||||
/* Get the left child index */
|
||||
int left(int i) {
|
||||
return 2 * i + 1;
|
||||
}
|
||||
|
||||
/* Get index of right child node */
|
||||
/* Get the right child index */
|
||||
int right(int i) {
|
||||
return 2 * i + 2;
|
||||
}
|
||||
|
||||
/* Get index of parent node */
|
||||
/* Get the parent index */
|
||||
int parent(int i) {
|
||||
return (i - 1) / 2; // Floor division
|
||||
return (i - 1) / 2; // Integer division truncates toward zero
|
||||
}
|
||||
|
||||
/* Starting from node i, heapify from bottom to top */
|
||||
/* Sift up starting from node i */
|
||||
void siftUp(int i) {
|
||||
while (true) {
|
||||
// Get parent node of node i
|
||||
// Get the parent of node i
|
||||
int p = parent(i);
|
||||
// When "crossing root node" or "node needs no repair", end heapify
|
||||
// Stop sifting when the root has been passed or the node needs no repair
|
||||
if (p < 0 || maxHeap[i] <= maxHeap[p])
|
||||
break;
|
||||
// Swap two nodes
|
||||
// Swap the two nodes
|
||||
swap(maxHeap[i], maxHeap[p]);
|
||||
// Loop upward heapify
|
||||
// Continue sifting up
|
||||
i = p;
|
||||
}
|
||||
}
|
||||
|
||||
/* Starting from node i, heapify from top to bottom */
|
||||
/* Sift down starting from node i */
|
||||
void siftDown(int i) {
|
||||
while (true) {
|
||||
// If node i is largest or indices l, r are out of bounds, no need to continue heapify, break
|
||||
// Find the node with the largest value among i, l, and r, and store its index in ma
|
||||
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;
|
||||
// Swap two nodes
|
||||
// Stop if node i is largest or both child indices l and r are out of bounds
|
||||
if (ma == i)
|
||||
break;
|
||||
swap(maxHeap[i], maxHeap[ma]);
|
||||
// Loop downwards heapification
|
||||
// Continue sifting down
|
||||
i = ma;
|
||||
}
|
||||
}
|
||||
|
||||
public:
|
||||
/* Constructor, build heap based on input list */
|
||||
/* Constructor: build a heap from the input list */
|
||||
MaxHeap(vector<int> nums) {
|
||||
// Add list elements to heap as is
|
||||
// Place the list elements in the heap without changing their order
|
||||
maxHeap = nums;
|
||||
// Heapify all nodes except leaf nodes
|
||||
// Sift down from every non-leaf node
|
||||
for (int i = parent(size() - 1); i >= 0; i--) {
|
||||
siftDown(i);
|
||||
}
|
||||
}
|
||||
|
||||
/* Get heap size */
|
||||
/* Get the heap size */
|
||||
int size() {
|
||||
return maxHeap.size();
|
||||
}
|
||||
|
||||
/* Check if heap is empty */
|
||||
/* Check whether the heap is empty */
|
||||
bool isEmpty() {
|
||||
return size() == 0;
|
||||
}
|
||||
|
||||
/* Access top element */
|
||||
/* Access the top element of the heap */
|
||||
int peek() {
|
||||
return maxHeap[0];
|
||||
}
|
||||
|
||||
/* Element enters heap */
|
||||
/* Push an element onto the heap */
|
||||
void push(int val) {
|
||||
// Add node
|
||||
// Add a node
|
||||
maxHeap.push_back(val);
|
||||
// Heapify from bottom to top
|
||||
// Sift up
|
||||
siftUp(size() - 1);
|
||||
}
|
||||
|
||||
/* Element exits heap */
|
||||
/* Pop an element from the heap */
|
||||
void pop() {
|
||||
// Handle empty case
|
||||
// Handle an empty heap
|
||||
if (isEmpty()) {
|
||||
throw out_of_range("Heap is empty");
|
||||
}
|
||||
// Delete node
|
||||
// Swap the root with the rightmost leaf on the last level (swap the first and last elements)
|
||||
swap(maxHeap[0], maxHeap[size() - 1]);
|
||||
// Remove node
|
||||
// Remove a node
|
||||
maxHeap.pop_back();
|
||||
// Return top element
|
||||
// Sift down
|
||||
siftDown(0);
|
||||
}
|
||||
|
||||
/* Driver Code*/
|
||||
/* Print the heap (binary tree)*/
|
||||
void print() {
|
||||
cout << "Heap array representation:";
|
||||
cout << "Array representation of the heap:";
|
||||
printVector(maxHeap);
|
||||
cout << "Heap tree representation:" << endl;
|
||||
cout << "Tree representation of the heap:" << endl;
|
||||
TreeNode *root = vectorToTree(maxHeap);
|
||||
printTree(root);
|
||||
freeMemoryTree(root);
|
||||
}
|
||||
};
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Consider negating the elements before entering the heap, which can reverse the size relationship, thus implementing max heap */
|
||||
/* Initialize a max heap */
|
||||
vector<int> vec{9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2};
|
||||
MaxHeap maxHeap(vec);
|
||||
cout << "\nAfter inputting list and building heap" << endl;
|
||||
cout << "\nAfter building a heap from the input list:" << endl;
|
||||
maxHeap.print();
|
||||
|
||||
/* Check if heap is empty */
|
||||
/* Get the top element of the heap */
|
||||
int peek = maxHeap.peek();
|
||||
cout << "\nHeap top element is " << peek << endl;
|
||||
cout << "\nTop element of the heap: " << peek << endl;
|
||||
|
||||
/* Element enters heap */
|
||||
/* Push an element onto the heap */
|
||||
int val = 7;
|
||||
maxHeap.push(val);
|
||||
cout << "\nAfter element " << val << " pushes to heap" << endl;
|
||||
cout << "\nAfter pushing element " << val << " onto the heap:" << endl;
|
||||
maxHeap.print();
|
||||
|
||||
/* Time complexity is O(n), not O(nlogn) */
|
||||
/* Pop the top element from the heap */
|
||||
peek = maxHeap.peek();
|
||||
maxHeap.pop();
|
||||
cout << "\nAfter heap top element " << peek << " pops from heap" << endl;
|
||||
cout << "\nAfter popping top element " << peek << " from the heap:" << endl;
|
||||
maxHeap.print();
|
||||
|
||||
/* Get heap size */
|
||||
/* Get the heap size */
|
||||
int size = maxHeap.size();
|
||||
cout << "\nHeap size is " << size << endl;
|
||||
cout << "\nNumber of elements in the heap: " << size << endl;
|
||||
|
||||
/* Check if heap is empty */
|
||||
/* Check whether the heap is empty */
|
||||
bool isEmpty = maxHeap.isEmpty();
|
||||
cout << "\nIs heap empty " << isEmpty << endl;
|
||||
cout << "\nIs the heap empty: " << isEmpty << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -6,17 +6,17 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Find the largest k elements in array based on heap */
|
||||
/* Use a heap to find the k largest elements in an array */
|
||||
priority_queue<int, vector<int>, greater<int>> topKHeap(vector<int> &nums, int k) {
|
||||
// Python's heapq module implements min heap by default
|
||||
// Initialize a min heap
|
||||
priority_queue<int, vector<int>, greater<int>> heap;
|
||||
// Enter the first k elements of array into heap
|
||||
// Push the first k array elements onto the heap
|
||||
for (int i = 0; i < k; i++) {
|
||||
heap.push(nums[i]);
|
||||
}
|
||||
// Starting from the (k+1)th element, maintain heap length as k
|
||||
// Starting with element k+1, keep the heap size at k
|
||||
for (int i = k; i < nums.size(); i++) {
|
||||
// If current element is greater than top element, top element exits heap, current element enters heap
|
||||
// If the current element is larger than the heap top, pop the top element and push the current element
|
||||
if (nums[i] > heap.top()) {
|
||||
heap.pop();
|
||||
heap.push(nums[i]);
|
||||
@@ -25,7 +25,7 @@ priority_queue<int, vector<int>, greater<int>> topKHeap(vector<int> &nums, int k
|
||||
return heap;
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
// Driver code
|
||||
int main() {
|
||||
vector<int> nums = {1, 7, 6, 3, 2};
|
||||
int k = 3;
|
||||
|
||||
@@ -6,52 +6,52 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Binary search (closed interval on both sides) */
|
||||
/* Binary search (closed interval) */
|
||||
int binarySearch(vector<int> &nums, int target) {
|
||||
// Initialize closed interval [0, n-1], i.e., i, j point to the first and last elements of the array
|
||||
// Initialize the closed interval [0, n-1], with i and j pointing to the first and last elements
|
||||
int i = 0, j = nums.size() - 1;
|
||||
// Loop, exit when the search interval is empty (empty when i > j)
|
||||
// Loop until the search interval is empty (when i > j)
|
||||
while (i <= 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]
|
||||
if (nums[m] < target) // In this case, target must be in [m+1, j] if it exists
|
||||
i = m + 1;
|
||||
else if (nums[m] > target) // This means target is in the interval [i, m-1]
|
||||
else if (nums[m] > target) // In this case, target must be in [i, m-1] if it exists
|
||||
j = m - 1;
|
||||
else // Found the target element, return its index
|
||||
else // The target element was found; return its index
|
||||
return m;
|
||||
}
|
||||
// Target element not found, return -1
|
||||
// The target element was 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 last element+1
|
||||
// Initialize the left-closed, right-open interval [0, n), with i at the first element and j one past the last
|
||||
int i = 0, j = nums.size();
|
||||
// Loop, exit when the search interval is empty (empty when i = j)
|
||||
// Loop until the search interval is empty (when i = j)
|
||||
while (i < 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)
|
||||
if (nums[m] < target) // In this case, target must be in [m+1, j) if it exists
|
||||
i = m + 1;
|
||||
else if (nums[m] > target) // This means target is in the interval [i, m)
|
||||
else if (nums[m] > target) // In this case, target must be in [i, m) if it exists
|
||||
j = m;
|
||||
else // Found the target element, return its index
|
||||
else // The target element was found; return its index
|
||||
return m;
|
||||
}
|
||||
// Target element not found, return -1
|
||||
// The target element was not found; return -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int target = 6;
|
||||
vector<int> nums = {1, 3, 6, 8, 12, 15, 23, 26, 31, 35};
|
||||
|
||||
/* Binary search (closed interval on both sides) */
|
||||
/* Binary search (closed interval) */
|
||||
int index = binarySearch(nums, target);
|
||||
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;
|
||||
|
||||
|
||||
@@ -6,60 +6,60 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Binary search for insertion point (with duplicate elements) */
|
||||
/* Find an insertion point using binary search (with duplicates) */
|
||||
int binarySearchInsertion(const vector<int> &nums, int target) {
|
||||
int i = 0, j = nums.size() - 1; // Initialize closed interval [0, n-1]
|
||||
int i = 0, j = nums.size() - 1; // Initialize the closed interval [0, n-1]
|
||||
while (i <= j) {
|
||||
int m = i + (j - i) / 2; // Calculate the midpoint index m
|
||||
if (nums[m] < target) {
|
||||
i = m + 1; // target is in the interval [m+1, j]
|
||||
i = m + 1; // Target must be in [m+1, j] if it exists
|
||||
} else {
|
||||
j = m - 1; // The rightmost element less than target is in the interval [i, m-1]
|
||||
j = m - 1; // Continue searching [i, m-1] for the insertion point before any equal elements
|
||||
}
|
||||
}
|
||||
// Return insertion point i
|
||||
return i;
|
||||
}
|
||||
|
||||
/* Binary search for the leftmost target */
|
||||
/* Find the leftmost occurrence of target using binary search */
|
||||
int binarySearchLeftEdge(vector<int> &nums, int target) {
|
||||
// Equivalent to finding the insertion point of target
|
||||
// This is equivalent to finding the insertion point of target
|
||||
int i = binarySearchInsertion(nums, target);
|
||||
// Target not found, return -1
|
||||
// If target was not found, return -1
|
||||
if (i == nums.size() || nums[i] != target) {
|
||||
return -1;
|
||||
}
|
||||
// Found target, return index i
|
||||
// Target was found; return index i
|
||||
return i;
|
||||
}
|
||||
|
||||
/* Binary search for the rightmost target */
|
||||
/* Find the rightmost occurrence of target using binary search */
|
||||
int binarySearchRightEdge(vector<int> &nums, int target) {
|
||||
// Convert to finding the leftmost target + 1
|
||||
// Reduce the problem to finding the leftmost insertion point of target + 1
|
||||
int i = binarySearchInsertion(nums, target + 1);
|
||||
// j points to the rightmost target, i points to the first element greater than target
|
||||
// j points to the rightmost target, while i points to the first element greater than target
|
||||
int j = i - 1;
|
||||
// Target not found, return -1
|
||||
// If target was not found, return -1
|
||||
if (j == -1 || nums[j] != target) {
|
||||
return -1;
|
||||
}
|
||||
// Found target, return index j
|
||||
// Target was found; return index j
|
||||
return j;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
// Array with duplicate elements
|
||||
// Array containing duplicate elements
|
||||
vector<int> nums = {1, 3, 6, 6, 6, 6, 6, 10, 12, 15};
|
||||
cout << "\nArray nums = ";
|
||||
printVector(nums);
|
||||
|
||||
// Binary search left and right boundaries
|
||||
// Find the left and right boundaries using binary search
|
||||
for (int target : {6, 7}) {
|
||||
int index = binarySearchLeftEdge(nums, target);
|
||||
cout << "Index of leftmost element " << target << " is " << index << endl;
|
||||
cout << "Leftmost occurrence of element " << target << " has index " << index << endl;
|
||||
index = binarySearchRightEdge(nums, target);
|
||||
cout << "Index of rightmost element " << target << " is " << index << endl;
|
||||
cout << "Rightmost occurrence of element " << target << " has index " << index << endl;
|
||||
}
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -6,60 +6,60 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Binary search for insertion point (no duplicate elements) */
|
||||
/* Find an insertion point using binary search (no duplicates) */
|
||||
int binarySearchInsertionSimple(vector<int> &nums, int target) {
|
||||
int i = 0, j = nums.size() - 1; // Initialize closed interval [0, n-1]
|
||||
int i = 0, j = nums.size() - 1; // Initialize the closed interval [0, n-1]
|
||||
while (i <= j) {
|
||||
int m = i + (j - i) / 2; // Calculate the midpoint index m
|
||||
if (nums[m] < target) {
|
||||
i = m + 1; // target is in the interval [m+1, j]
|
||||
i = m + 1; // Target must be in [m+1, j] if it exists
|
||||
} else if (nums[m] > target) {
|
||||
j = m - 1; // target is in the interval [i, m-1]
|
||||
j = m - 1; // Target must be in [i, m-1] if it exists
|
||||
} else {
|
||||
return m; // Found target, return insertion point m
|
||||
return m; // Target was found; return insertion point m
|
||||
}
|
||||
}
|
||||
// Target not found, return insertion point i
|
||||
// Target was not found; return insertion point i
|
||||
return i;
|
||||
}
|
||||
|
||||
/* Binary search for insertion point (with duplicate elements) */
|
||||
/* Find an insertion point using binary search (with duplicates) */
|
||||
int binarySearchInsertion(vector<int> &nums, int target) {
|
||||
int i = 0, j = nums.size() - 1; // Initialize closed interval [0, n-1]
|
||||
int i = 0, j = nums.size() - 1; // Initialize the closed interval [0, n-1]
|
||||
while (i <= j) {
|
||||
int m = i + (j - i) / 2; // Calculate the midpoint index m
|
||||
if (nums[m] < target) {
|
||||
i = m + 1; // target is in the interval [m+1, j]
|
||||
i = m + 1; // Target must be in [m+1, j] if it exists
|
||||
} else if (nums[m] > target) {
|
||||
j = m - 1; // target is in the interval [i, m-1]
|
||||
j = m - 1; // Target must be in [i, m-1] if it exists
|
||||
} else {
|
||||
j = m - 1; // The rightmost element less than target is in the interval [i, m-1]
|
||||
j = m - 1; // Continue searching [i, m-1] for the insertion point before any equal elements
|
||||
}
|
||||
}
|
||||
// Return insertion point i
|
||||
return i;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
// Array without duplicate elements
|
||||
// Array with no duplicate elements
|
||||
vector<int> nums = {1, 3, 6, 8, 12, 15, 23, 26, 31, 35};
|
||||
cout << "\nArray nums = ";
|
||||
printVector(nums);
|
||||
// Binary search for insertion point
|
||||
// Find an insertion point using binary search
|
||||
for (int target : {6, 9}) {
|
||||
int index = binarySearchInsertionSimple(nums, target);
|
||||
cout << "Insertion point index for element " << target << " is " << index << endl;
|
||||
cout << "Element " << target << " has insertion index " << index << endl;
|
||||
}
|
||||
|
||||
// Array with duplicate elements
|
||||
// Array containing duplicate elements
|
||||
nums = {1, 3, 6, 6, 6, 6, 6, 10, 12, 15};
|
||||
cout << "\nArray nums = ";
|
||||
printVector(nums);
|
||||
// Binary search for insertion point
|
||||
// Find an insertion point using binary search
|
||||
for (int target : {2, 6, 20}) {
|
||||
int index = binarySearchInsertion(nums, target);
|
||||
cout << "Insertion point index for element " << target << " is " << index << endl;
|
||||
cout << "Element " << target << " has insertion index " << index << endl;
|
||||
}
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -6,48 +6,48 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Hash search (array) */
|
||||
/* Hash-based search (array) */
|
||||
int hashingSearchArray(unordered_map<int, int> map, int target) {
|
||||
// Hash table's key: target element, value: index
|
||||
// If this key does not exist in the hash table, return -1
|
||||
// Hash table key: target element; value: index
|
||||
// Return -1 if the hash table does not contain this key
|
||||
if (map.find(target) == map.end())
|
||||
return -1;
|
||||
return map[target];
|
||||
}
|
||||
|
||||
/* Hash search (linked list) */
|
||||
/* Hash-based search (linked list) */
|
||||
ListNode *hashingSearchLinkedList(unordered_map<int, ListNode *> map, int target) {
|
||||
// Hash table key: target node value, value: node object
|
||||
// Return nullptr if key does not exist in hash table
|
||||
// Hash table key: target node value; value: node object
|
||||
// Return nullptr if this key is absent from the hash table
|
||||
if (map.find(target) == map.end())
|
||||
return nullptr;
|
||||
return map[target];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int target = 3;
|
||||
|
||||
/* Hash search (array) */
|
||||
/* Hash-based search (array) */
|
||||
vector<int> nums = {1, 5, 3, 2, 4, 7, 5, 9, 10, 8};
|
||||
// Initialize hash table
|
||||
// Initialize the hash table
|
||||
unordered_map<int, int> map;
|
||||
for (int i = 0; i < nums.size(); i++) {
|
||||
map[nums[i]] = i; // key: element, value: index
|
||||
map[nums[i]] = i; // key: element; value: index
|
||||
}
|
||||
int index = hashingSearchArray(map, target);
|
||||
cout << "Index of target element 3 = " << index << endl;
|
||||
|
||||
/* Hash search (linked list) */
|
||||
/* Hash-based search (linked list) */
|
||||
ListNode *head = vecToLinkedList(nums);
|
||||
// Initialize hash table
|
||||
// Initialize the hash table
|
||||
unordered_map<int, ListNode *> map1;
|
||||
while (head != nullptr) {
|
||||
map1[head->val] = head; // key: node value, value: node
|
||||
map1[head->val] = head; // key: node value; value: node
|
||||
head = head->next;
|
||||
}
|
||||
ListNode *node = hashingSearchLinkedList(map1, target);
|
||||
cout << "Node object corresponding to target node value 3 is " << node << endl;
|
||||
cout << "The node object corresponding to target value 3 is " << node << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -8,13 +8,13 @@
|
||||
|
||||
/* Linear search (array) */
|
||||
int linearSearchArray(vector<int> &nums, int target) {
|
||||
// Traverse array
|
||||
// Traverse the array
|
||||
for (int i = 0; i < nums.size(); i++) {
|
||||
// Found the target element, return its index
|
||||
// The target element was found; return its index
|
||||
if (nums[i] == target)
|
||||
return i;
|
||||
}
|
||||
// Target element not found, return -1
|
||||
// The target element was not found; return -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
@@ -22,28 +22,28 @@ int linearSearchArray(vector<int> &nums, int target) {
|
||||
ListNode *linearSearchLinkedList(ListNode *head, int target) {
|
||||
// Traverse the linked list
|
||||
while (head != nullptr) {
|
||||
// Found the target node, return it
|
||||
// The target node was found; return it
|
||||
if (head->val == target)
|
||||
return head;
|
||||
head = head->next;
|
||||
}
|
||||
// Target node not found, return nullptr
|
||||
// The target node was not found; return nullptr
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int target = 3;
|
||||
|
||||
/* Perform linear search in array */
|
||||
/* Perform linear search on the array */
|
||||
vector<int> nums = {1, 5, 3, 2, 4, 7, 5, 9, 10, 8};
|
||||
int index = linearSearchArray(nums, target);
|
||||
cout << "Index of target element 3 = " << index << endl;
|
||||
|
||||
/* Perform linear search in linked list */
|
||||
/* Perform linear search on the linked list */
|
||||
ListNode *head = vecToLinkedList(nums);
|
||||
ListNode *node = linearSearchLinkedList(head, target);
|
||||
cout << "Node object corresponding to target node value 3 is " << node << endl;
|
||||
cout << "The node object corresponding to target value 3 is " << node << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -6,10 +6,10 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Method 1: Brute force enumeration */
|
||||
/* Method 1: brute-force enumeration */
|
||||
vector<int> twoSumBruteForce(vector<int> &nums, int target) {
|
||||
int size = nums.size();
|
||||
// Two nested loops, time complexity is O(n^2)
|
||||
// Two nested loops give a time complexity of 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 2: 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)
|
||||
// The auxiliary hash table uses O(n) space
|
||||
unordered_map<int, int> dic;
|
||||
// Single loop, time complexity is O(n)
|
||||
// A single loop gives a time complexity of O(n)
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (dic.find(target - nums[i]) != dic.end()) {
|
||||
return {dic[target - nums[i]], i};
|
||||
@@ -34,20 +34,20 @@ vector<int> twoSumHashTable(vector<int> &nums, int target) {
|
||||
return {};
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
// ======= Test Case =======
|
||||
// ======= Test case =======
|
||||
vector<int> nums = {2, 7, 11, 15};
|
||||
int target = 13;
|
||||
|
||||
// ====== Driver Code ======
|
||||
// ====== Driver code ======
|
||||
// Method 1
|
||||
vector<int> res = twoSumBruteForce(nums, target);
|
||||
cout << "Method 1 res = ";
|
||||
cout << "Method 1: res = ";
|
||||
printVector(res);
|
||||
// Method 2
|
||||
res = twoSumHashTable(nums, target);
|
||||
cout << "Method 2 res = ";
|
||||
cout << "Method 2: res = ";
|
||||
printVector(res);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -8,13 +8,13 @@
|
||||
|
||||
/* Bubble sort */
|
||||
void bubbleSort(vector<int> &nums) {
|
||||
// Outer loop: unsorted range is [0, i]
|
||||
// Outer loop: the 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 rightmost end of that range
|
||||
// Inner loop: move the largest element in the unsorted range [0, i] to its right end through swaps
|
||||
for (int j = 0; j < i; j++) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// Swap nums[j] and nums[j + 1]
|
||||
// Using std::swap() function here
|
||||
// Use the std::swap() function here
|
||||
swap(nums[j], nums[j + 1]);
|
||||
}
|
||||
}
|
||||
@@ -23,33 +23,33 @@ void bubbleSort(vector<int> &nums) {
|
||||
|
||||
/* Bubble sort (flag optimization)*/
|
||||
void bubbleSortWithFlag(vector<int> &nums) {
|
||||
// Outer loop: unsorted range is [0, i]
|
||||
// Outer loop: the 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 rightmost end of that range
|
||||
bool flag = false; // Initialize the flag
|
||||
// Inner loop: move the largest element in the unsorted range [0, i] to its right end through swaps
|
||||
for (int j = 0; j < i; j++) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// Swap nums[j] and nums[j + 1]
|
||||
// Using std::swap() function here
|
||||
// Use the std::swap() function here
|
||||
swap(nums[j], nums[j + 1]);
|
||||
flag = true; // Record element swap
|
||||
flag = true; // Record that a swap occurred
|
||||
}
|
||||
}
|
||||
if (!flag)
|
||||
break; // No elements were swapped in this round of "bubbling", exit directly
|
||||
break; // Exit immediately if this pass made no swaps
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
vector<int> nums = {4, 1, 3, 1, 5, 2};
|
||||
bubbleSort(nums);
|
||||
cout << "After bubble sort completes, nums = ";
|
||||
cout << "After bubble sort, nums = ";
|
||||
printVector(nums);
|
||||
|
||||
vector<int> nums1 = {4, 1, 3, 1, 5, 2};
|
||||
bubbleSortWithFlag(nums1);
|
||||
cout << "After bubble sort completes, nums1 = ";
|
||||
cout << "After bubble sort, nums1 = ";
|
||||
printVector(nums1);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -8,22 +8,22 @@
|
||||
|
||||
/* Bucket sort */
|
||||
void bucketSort(vector<float> &nums) {
|
||||
// Initialize k = n/2 buckets, expected to allocate 2 elements per bucket
|
||||
// Initialize k = n/2 buckets, expecting 2 elements per bucket
|
||||
int k = nums.size() / 2;
|
||||
vector<vector<float>> buckets(k);
|
||||
// 1. Distribute array elements into various buckets
|
||||
// 1. Distribute the array elements among the buckets
|
||||
for (float num : nums) {
|
||||
// Input data range is [0, 1), use num * k to map to index range [0, k-1]
|
||||
// The input range is [0, 1); use num * k to map each value to an index in [0, k-1]
|
||||
int i = num * k;
|
||||
// Add num to bucket bucket_idx
|
||||
// Add num to bucket i
|
||||
buckets[i].push_back(num);
|
||||
}
|
||||
// 2. Sort each bucket
|
||||
for (vector<float> &bucket : buckets) {
|
||||
// Use built-in sorting function, can also replace with other sorting algorithms
|
||||
// Use the built-in sorting function, or replace it with another sorting algorithm
|
||||
sort(bucket.begin(), bucket.end());
|
||||
}
|
||||
// 3. Traverse buckets to merge results
|
||||
// 3. Traverse the buckets to combine the results
|
||||
int i = 0;
|
||||
for (vector<float> &bucket : buckets) {
|
||||
for (float num : bucket) {
|
||||
@@ -32,12 +32,12 @@ void bucketSort(vector<float> &nums) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
// Assume input data is floating point, interval [0, 1)
|
||||
// Assume the input consists of floating-point numbers in [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 completes, nums = ";
|
||||
cout << "After bucket sort, nums = ";
|
||||
printVector(nums);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -7,20 +7,20 @@
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Counting sort */
|
||||
// Simple implementation, cannot be used for sorting objects
|
||||
// Simple implementation; cannot be used to sort objects
|
||||
void countingSortNaive(vector<int> &nums) {
|
||||
// 1. Count the maximum element m in the array
|
||||
// 1. Find the maximum array element m
|
||||
int m = 0;
|
||||
for (int num : nums) {
|
||||
m = max(m, num);
|
||||
}
|
||||
// 2. Count the occurrence of each number
|
||||
// counter[num] represents the occurrence of num
|
||||
// 2. Count the occurrences of each number
|
||||
// counter[num] is the number of occurrences of num
|
||||
vector<int> counter(m + 1, 0);
|
||||
for (int num : nums) {
|
||||
counter[num]++;
|
||||
}
|
||||
// 3. Traverse counter, filling each element back into the original array nums
|
||||
// 3. Traverse counter and fill the original array nums with the elements
|
||||
int i = 0;
|
||||
for (int num = 0; num < m + 1; num++) {
|
||||
for (int j = 0; j < counter[num]; j++, i++) {
|
||||
@@ -30,47 +30,47 @@ void countingSortNaive(vector<int> &nums) {
|
||||
}
|
||||
|
||||
/* Counting sort */
|
||||
// Complete implementation, can sort objects and is a stable sort
|
||||
// Stable implementation that can be adapted to sort objects
|
||||
void countingSort(vector<int> &nums) {
|
||||
// 1. Count the maximum element m in the array
|
||||
// 1. Find the maximum array element m
|
||||
int m = 0;
|
||||
for (int num : nums) {
|
||||
m = max(m, num);
|
||||
}
|
||||
// 2. Count the occurrence of each number
|
||||
// counter[num] represents the occurrence of num
|
||||
// 2. Count the occurrences of each number
|
||||
// counter[num] is the number of occurrences of num
|
||||
vector<int> counter(m + 1, 0);
|
||||
for (int num : nums) {
|
||||
counter[num]++;
|
||||
}
|
||||
// 3. Calculate the prefix sum of counter, converting "occurrence count" to "tail index"
|
||||
// counter[num]-1 is the last index where num appears in res
|
||||
// 3. Compute prefix sums of counter to convert occurrence counts into end positions
|
||||
// That is, counter[num]-1 is the index of the last occurrence of num in res
|
||||
for (int i = 0; i < m; i++) {
|
||||
counter[i + 1] += counter[i];
|
||||
}
|
||||
// 4. Traverse nums in reverse order, placing each element into the result array res
|
||||
// Initialize the array res to record results
|
||||
// 4. Traverse nums in reverse and place each element in the result array res
|
||||
// Initialize array res to store the result
|
||||
int n = nums.size();
|
||||
vector<int> res(n);
|
||||
for (int i = n - 1; i >= 0; i--) {
|
||||
int num = nums[i];
|
||||
res[counter[num] - 1] = num; // Place num at the corresponding index
|
||||
counter[num]--; // Decrement the prefix sum by 1, getting the next index to place num
|
||||
counter[num]--; // Decrement the prefix sum by 1 to determine where to place the next occurrence of num
|
||||
}
|
||||
// Use result array res to overwrite the original array nums
|
||||
// Overwrite the original array nums with the result array res
|
||||
nums = res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
vector<int> nums = {1, 0, 1, 2, 0, 4, 0, 2, 2, 4};
|
||||
countingSortNaive(nums);
|
||||
cout << "After counting sort (cannot sort objects) completes, nums = ";
|
||||
cout << "After counting sort (without support for objects), nums = ";
|
||||
printVector(nums);
|
||||
|
||||
vector<int> nums1 = {1, 0, 1, 2, 0, 4, 0, 2, 2, 4};
|
||||
countingSort(nums1);
|
||||
cout << "After counting sort completes, nums1 = ";
|
||||
cout << "After counting sort, nums1 = ";
|
||||
printVector(nums1);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -6,10 +6,10 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Heap length is n, start heapifying node i, from top to bottom */
|
||||
/* Sift down from node i in a heap of size n */
|
||||
void siftDown(vector<int> &nums, int n, int i) {
|
||||
while (true) {
|
||||
// If node i is largest or indices l, r are out of bounds, no need to continue heapify, break
|
||||
// Find the node with the largest value among i, l, and r, and store its index in ma
|
||||
int l = 2 * i + 1;
|
||||
int r = 2 * i + 2;
|
||||
int ma = i;
|
||||
@@ -17,37 +17,37 @@ void siftDown(vector<int> &nums, int n, int i) {
|
||||
ma = l;
|
||||
if (r < n && nums[r] > nums[ma])
|
||||
ma = r;
|
||||
// Swap two nodes
|
||||
// Stop if node i is largest or both child indices l and r are out of bounds
|
||||
if (ma == i) {
|
||||
break;
|
||||
}
|
||||
// Swap two nodes
|
||||
// Swap the two nodes
|
||||
swap(nums[i], nums[ma]);
|
||||
// Loop downwards heapification
|
||||
// Continue sifting down
|
||||
i = ma;
|
||||
}
|
||||
}
|
||||
|
||||
/* Heap sort */
|
||||
void heapSort(vector<int> &nums) {
|
||||
// Build heap operation: heapify all nodes except leaves
|
||||
// Build the heap by sifting down from every non-leaf node
|
||||
for (int i = nums.size() / 2 - 1; i >= 0; --i) {
|
||||
siftDown(nums, nums.size(), i);
|
||||
}
|
||||
// Extract the largest element from the heap and repeat for n-1 rounds
|
||||
// Extract the largest element from the heap, repeating for n-1 rounds
|
||||
for (int i = nums.size() - 1; i > 0; --i) {
|
||||
// Delete node
|
||||
// Swap the root with the rightmost leaf on the last level (the first and last elements of the current heap)
|
||||
swap(nums[0], nums[i]);
|
||||
// Start heapifying the root node, from top to bottom
|
||||
// Sift down starting at the root
|
||||
siftDown(nums, i, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
vector<int> nums = {4, 1, 3, 1, 5, 2};
|
||||
heapSort(nums);
|
||||
cout << "After heap sort completes, nums = ";
|
||||
cout << "After heap sort, nums = ";
|
||||
printVector(nums);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -8,23 +8,23 @@
|
||||
|
||||
/* Insertion sort */
|
||||
void insertionSort(vector<int> &nums) {
|
||||
// Outer loop: sorted interval is [0, i-1]
|
||||
// Outer loop: the sorted range 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 interval [0, i-1]
|
||||
// Inner loop: insert base at the correct position in the sorted range [0, i-1]
|
||||
while (j >= 0 && nums[j] > base) {
|
||||
nums[j + 1] = nums[j]; // Move nums[j] to the right by one position
|
||||
nums[j + 1] = nums[j]; // Shift nums[j] one position to the right
|
||||
j--;
|
||||
}
|
||||
nums[j + 1] = base; // Assign base to the correct position
|
||||
nums[j + 1] = base; // Place base at the correct position
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
vector<int> nums = {4, 1, 3, 1, 5, 2};
|
||||
insertionSort(nums);
|
||||
cout << "After insertion sort completes, nums = ";
|
||||
cout << "After insertion sort, nums = ";
|
||||
printVector(nums);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -6,14 +6,14 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Merge left subarray and right subarray */
|
||||
/* Merge the left and right subarrays */
|
||||
void merge(vector<int> &nums, int left, int mid, int right) {
|
||||
// Left subarray interval is [left, mid], right subarray interval is [mid+1, right]
|
||||
// Create a temporary array tmp to store the merged results
|
||||
// The left subarray spans [left, mid], and the right subarray spans [mid+1, right]
|
||||
// Create a temporary array tmp to store the merged result
|
||||
vector<int> tmp(right - left + 1);
|
||||
// Initialize the start indices of the left and right subarrays
|
||||
// Initialize the starting indices of the left and right subarrays
|
||||
int i = left, j = mid + 1, k = 0;
|
||||
// While both subarrays still have elements, compare and copy the smaller element into the temporary array
|
||||
// While both subarrays have elements remaining, compare them and copy the smaller element into the temporary array
|
||||
while (i <= mid && j <= right) {
|
||||
if (nums[i] <= nums[j])
|
||||
tmp[k++] = nums[i++];
|
||||
@@ -27,7 +27,7 @@ void merge(vector<int> &nums, int left, int mid, int right) {
|
||||
while (j <= right) {
|
||||
tmp[k++] = nums[j++];
|
||||
}
|
||||
// Copy the elements from the temporary array tmp back to the original array nums at the corresponding interval
|
||||
// Copy the elements of temporary array tmp back into the corresponding range of the original array nums
|
||||
for (k = 0; k < tmp.size(); k++) {
|
||||
nums[left + k] = tmp[k];
|
||||
}
|
||||
@@ -35,23 +35,23 @@ void merge(vector<int> &nums, int left, int mid, int right) {
|
||||
|
||||
/* Merge sort */
|
||||
void mergeSort(vector<int> &nums, int left, int right) {
|
||||
// Termination condition
|
||||
// Base case
|
||||
if (left >= right)
|
||||
return; // Terminate recursion when subarray length is 1
|
||||
// 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
|
||||
// Merge stage
|
||||
return; // Stop recursing when the subarray has at most one element
|
||||
// Divide phase
|
||||
int mid = left + (right - left) / 2; // Calculate the midpoint
|
||||
mergeSort(nums, left, mid); // Recurse on the left subarray
|
||||
mergeSort(nums, mid + 1, right); // Recurse on the right subarray
|
||||
// Merge phase
|
||||
merge(nums, left, mid, right);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
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 completes, nums = ";
|
||||
cout << "After merge sort, nums = ";
|
||||
printVector(nums);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -9,30 +9,30 @@
|
||||
/* Quick sort class */
|
||||
class QuickSort {
|
||||
private:
|
||||
/* Sentinel partition */
|
||||
/* Two-pointer partitioning */
|
||||
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--; // Scan 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
|
||||
i++; // Scan from left to right for the first element larger than the pivot
|
||||
swap(nums[i], nums[j]); // Swap these two elements
|
||||
}
|
||||
swap(nums[i], nums[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 into the boundary position between the two subarrays
|
||||
return i; // Return the pivot index
|
||||
}
|
||||
|
||||
public:
|
||||
/* Quick sort */
|
||||
static void quickSort(vector<int> &nums, int left, int right) {
|
||||
// Terminate recursion when subarray length is 1
|
||||
// Stop recursing when the subarray has at most one element
|
||||
if (left >= right)
|
||||
return;
|
||||
// Sentinel partition
|
||||
// Two-pointer partitioning
|
||||
int pivot = partition(nums, left, right);
|
||||
// Recursively process the left subarray and right subarray
|
||||
// Recurse on the left and right subarrays
|
||||
quickSort(nums, left, pivot - 1);
|
||||
quickSort(nums, pivot + 1, right);
|
||||
}
|
||||
@@ -45,40 +45,40 @@ class QuickSortMedian {
|
||||
static int medianThree(vector<int> &nums, int left, int mid, int right) {
|
||||
int l = nums[left], m = nums[mid], r = nums[right];
|
||||
if ((l <= m && m <= r) || (r <= m && m <= l))
|
||||
return mid; // m is between l and r
|
||||
return mid; // m lies between l and r
|
||||
if ((m <= l && l <= r) || (r <= l && l <= m))
|
||||
return left; // l is between m and r
|
||||
return left; // l lies between m and r
|
||||
return right;
|
||||
}
|
||||
|
||||
/* Sentinel partition (median of three) */
|
||||
/* Two-pointer partitioning (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 the median into the leftmost position of the current subarray
|
||||
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--; // Scan 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
|
||||
i++; // Scan from left to right for the first element larger than the pivot
|
||||
swap(nums[i], nums[j]); // Swap these two elements
|
||||
}
|
||||
swap(nums[i], nums[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 into the boundary position between the two subarrays
|
||||
return i; // Return the pivot index
|
||||
}
|
||||
|
||||
public:
|
||||
/* Quick sort */
|
||||
static void quickSort(vector<int> &nums, int left, int right) {
|
||||
// Terminate recursion when subarray length is 1
|
||||
// Stop recursing when the subarray has at most one element
|
||||
if (left >= right)
|
||||
return;
|
||||
// Sentinel partition
|
||||
// Two-pointer partitioning
|
||||
int pivot = partition(nums, left, right);
|
||||
// Recursively process the left subarray and right subarray
|
||||
// Recurse on the left and right subarrays
|
||||
quickSort(nums, left, pivot - 1);
|
||||
quickSort(nums, pivot + 1, right);
|
||||
}
|
||||
@@ -87,58 +87,58 @@ class QuickSortMedian {
|
||||
/* Quick sort class (recursion depth optimization) */
|
||||
class QuickSortTailCall {
|
||||
private:
|
||||
/* Sentinel partition */
|
||||
/* Two-pointer partitioning */
|
||||
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--; // Scan 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
|
||||
i++; // Scan from left to right for the first element larger than the pivot
|
||||
swap(nums[i], nums[j]); // Swap these two elements
|
||||
}
|
||||
swap(nums[i], nums[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 into the boundary position between the two subarrays
|
||||
return i; // Return the pivot index
|
||||
}
|
||||
|
||||
public:
|
||||
/* Quick sort (recursion depth optimization) */
|
||||
static void quickSort(vector<int> &nums, int left, int right) {
|
||||
// Terminate when subarray length is 1
|
||||
// Stop when the subarray has at most one element
|
||||
while (left < right) {
|
||||
// Sentinel partition operation
|
||||
// Perform two-pointer partitioning
|
||||
int pivot = partition(nums, left, right);
|
||||
// Perform quick sort on the shorter of the two subarrays
|
||||
// Apply quick sort to the shorter of the two subarrays
|
||||
if (pivot - left < right - pivot) {
|
||||
quickSort(nums, left, pivot - 1); // Recursively sort the left subarray
|
||||
left = pivot + 1; // Remaining unsorted interval is [pivot + 1, right]
|
||||
left = pivot + 1; // The remaining unsorted range is [pivot + 1, right]
|
||||
} else {
|
||||
quickSort(nums, pivot + 1, right); // Recursively sort the right subarray
|
||||
right = pivot - 1; // Remaining unsorted interval is [left, pivot - 1]
|
||||
right = pivot - 1; // The remaining unsorted range is [left, pivot - 1]
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Quick sort */
|
||||
vector<int> nums{2, 4, 1, 0, 3, 5};
|
||||
QuickSort::quickSort(nums, 0, nums.size() - 1);
|
||||
cout << "After quick sort completes, nums = ";
|
||||
cout << "After quick sort, nums = ";
|
||||
printVector(nums);
|
||||
|
||||
/* Quick sort (recursion depth optimization) */
|
||||
/* Quick sort (median pivot optimization) */
|
||||
vector<int> nums1 = {2, 4, 1, 0, 3, 5};
|
||||
QuickSortMedian::quickSort(nums1, 0, nums1.size() - 1);
|
||||
cout << "After quick sort (median pivot optimization), nums = ";
|
||||
cout << "After quick sort with median-of-three pivot selection, nums1 = ";
|
||||
printVector(nums1);
|
||||
|
||||
/* Quick sort (recursion depth optimization) */
|
||||
vector<int> nums2 = {2, 4, 1, 0, 3, 5};
|
||||
QuickSortTailCall::quickSort(nums2, 0, nums2.size() - 1);
|
||||
cout << "After quick sort (recursion depth optimization), nums = ";
|
||||
cout << "After quick sort with recursion-depth optimization, nums2 = ";
|
||||
printVector(nums2);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -6,59 +6,59 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Get the k-th digit of element num, where exp = 10^(k-1) */
|
||||
/* Get the k-th digit of num, where exp = 10^(k-1) */
|
||||
int digit(int num, int exp) {
|
||||
// Passing exp instead of k can avoid repeated expensive exponentiation here
|
||||
// Passing exp instead of k avoids repeatedly performing expensive exponentiation here
|
||||
return (num / exp) % 10;
|
||||
}
|
||||
|
||||
/* Counting sort (based on nums k-th digit) */
|
||||
/* Counting sort (sort nums by the k-th digit) */
|
||||
void countingSortDigit(vector<int> &nums, int exp) {
|
||||
// Decimal digit range is 0~9, therefore need a bucket array of length 10
|
||||
// Decimal digits range from 0 to 9, so the bucket array needs length 10
|
||||
vector<int> counter(10, 0);
|
||||
int n = nums.size();
|
||||
// Count the occurrence of digits 0~9
|
||||
// Count the occurrences of each digit from 0 to 9
|
||||
for (int i = 0; i < n; i++) {
|
||||
int d = digit(nums[i], exp); // Get the k-th digit of nums[i], noted as d
|
||||
counter[d]++; // Count the occurrence of digit d
|
||||
int d = digit(nums[i], exp); // Get the k-th digit of nums[i] and store it in d
|
||||
counter[d]++; // Count the occurrences of digit d
|
||||
}
|
||||
// Calculate prefix sum, converting "occurrence count" into "array index"
|
||||
// Compute prefix sums to convert occurrence counts into array positions
|
||||
for (int i = 1; i < 10; i++) {
|
||||
counter[i] += counter[i - 1];
|
||||
}
|
||||
// Traverse in reverse, based on bucket statistics, place each element into res
|
||||
// Traverse in reverse and place each element into res according to the bucket counts
|
||||
vector<int> res(n, 0);
|
||||
for (int i = n - 1; i >= 0; i--) {
|
||||
int d = digit(nums[i], exp);
|
||||
int j = counter[d] - 1; // Get the index j for d in the array
|
||||
int j = counter[d] - 1; // Get the destination index j for digit d in the array
|
||||
res[j] = nums[i]; // Place the current element at index j
|
||||
counter[d]--; // Decrease the count of d by 1
|
||||
counter[d]--; // Decrease the count for d by 1
|
||||
}
|
||||
// Use result to overwrite the original array nums
|
||||
// Overwrite the original array nums with the result
|
||||
for (int i = 0; i < n; i++)
|
||||
nums[i] = res[i];
|
||||
}
|
||||
|
||||
/* Radix sort */
|
||||
void radixSort(vector<int> &nums) {
|
||||
// Get the maximum element of the array, used to determine the maximum number of digits
|
||||
// Get the largest array element to determine the maximum number of digits
|
||||
int m = *max_element(nums.begin(), nums.end());
|
||||
// Traverse from the lowest to the highest digit
|
||||
// Process digits from least significant to most significant
|
||||
for (int exp = 1; exp <= m; exp *= 10)
|
||||
// Perform counting sort on the k-th digit of array elements
|
||||
// Apply counting sort to the k-th digit of the array elements
|
||||
// k = 1 -> exp = 1
|
||||
// k = 2 -> exp = 10
|
||||
// i.e., exp = 10^(k-1)
|
||||
// That is, exp = 10^(k-1)
|
||||
countingSortDigit(nums, exp);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
// Radix sort
|
||||
vector<int> nums = {10546151, 35663510, 42865989, 34862445, 81883077,
|
||||
88906420, 72429244, 30524779, 82060337, 63832996};
|
||||
radixSort(nums);
|
||||
cout << "After radix sort completes, nums = ";
|
||||
cout << "After radix sort, nums = ";
|
||||
printVector(nums);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -9,25 +9,25 @@
|
||||
/* Selection sort */
|
||||
void selectionSort(vector<int> &nums) {
|
||||
int n = nums.size();
|
||||
// Outer loop: unsorted interval is [i, n-1]
|
||||
// Outer loop: the unsorted range is [i, n-1]
|
||||
for (int i = 0; i < n - 1; i++) {
|
||||
// Inner loop: find the smallest element within the unsorted interval
|
||||
// Inner loop: find the smallest element in the unsorted range
|
||||
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 interval
|
||||
// Swap the smallest element with the first element of the unsorted range
|
||||
swap(nums[i], nums[k]);
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
vector<int> nums = {4, 1, 3, 1, 5, 2};
|
||||
selectionSort(nums);
|
||||
|
||||
cout << "After selection sort completes, nums = ";
|
||||
cout << "After selection sort, nums = ";
|
||||
printVector(nums);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -6,12 +6,12 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Double-ended queue based on circular array implementation */
|
||||
/* Deque implemented with a circular array */
|
||||
class ArrayDeque {
|
||||
private:
|
||||
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
|
||||
vector<int> nums; // Array for storing deque elements
|
||||
int front; // Front index, identifying the first element
|
||||
int queSize; // Deque size
|
||||
|
||||
public:
|
||||
/* Constructor */
|
||||
@@ -20,91 +20,91 @@ class ArrayDeque {
|
||||
front = queSize = 0;
|
||||
}
|
||||
|
||||
/* Get the capacity of the double-ended queue */
|
||||
/* Get the deque capacity */
|
||||
int capacity() {
|
||||
return nums.size();
|
||||
}
|
||||
|
||||
/* Get the length of the double-ended queue */
|
||||
/* Get the deque size */
|
||||
int size() {
|
||||
return queSize;
|
||||
}
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
/* Check whether the deque is empty */
|
||||
bool isEmpty() {
|
||||
return queSize == 0;
|
||||
}
|
||||
|
||||
/* Calculate circular array index */
|
||||
/* Calculate an index in the circular array */
|
||||
int index(int i) {
|
||||
// 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
|
||||
// Use modulo to connect the end of the array to its beginning
|
||||
// When i passes the end of the array, wrap around to the beginning
|
||||
// When i passes the beginning of the array, wrap around to the end
|
||||
return (i + capacity()) % capacity();
|
||||
}
|
||||
|
||||
/* Front of the queue enqueue */
|
||||
/* Enqueue at the front */
|
||||
void pushFirst(int num) {
|
||||
if (queSize == capacity()) {
|
||||
cout << "Double-ended queue is full" << endl;
|
||||
cout << "Deque is full" << endl;
|
||||
return;
|
||||
}
|
||||
// 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
|
||||
// Move the front index one position to the left
|
||||
// Use modulo to wrap front to the end when it passes the beginning of the array
|
||||
front = index(front - 1);
|
||||
// Add num to front of queue
|
||||
// Add num to the front
|
||||
nums[front] = num;
|
||||
queSize++;
|
||||
}
|
||||
|
||||
/* Rear of the queue enqueue */
|
||||
/* Enqueue at the rear */
|
||||
void pushLast(int num) {
|
||||
if (queSize == capacity()) {
|
||||
cout << "Double-ended queue is full" << endl;
|
||||
cout << "Deque is full" << endl;
|
||||
return;
|
||||
}
|
||||
// Use modulo operation to wrap rear around to the head after passing the tail of the array
|
||||
// Calculate the rear index, one position past the last element
|
||||
int rear = index(front + queSize);
|
||||
// Front pointer moves one position backward
|
||||
// Add num to the rear
|
||||
nums[rear] = num;
|
||||
queSize++;
|
||||
}
|
||||
|
||||
/* Rear of the queue dequeue */
|
||||
/* Dequeue from the front */
|
||||
int popFirst() {
|
||||
int num = peekFirst();
|
||||
// Move front pointer backward by one position
|
||||
// Advance the front index by one position
|
||||
front = index(front + 1);
|
||||
queSize--;
|
||||
return num;
|
||||
}
|
||||
|
||||
/* Access rear of the queue element */
|
||||
/* Dequeue from the rear */
|
||||
int popLast() {
|
||||
int num = peekLast();
|
||||
queSize--;
|
||||
return num;
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
/* Access the front element */
|
||||
int peekFirst() {
|
||||
if (isEmpty())
|
||||
throw out_of_range("Deque is empty");
|
||||
return nums[front];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Access the rear element */
|
||||
int peekLast() {
|
||||
if (isEmpty())
|
||||
throw out_of_range("Deque is empty");
|
||||
// Initialize double-ended queue
|
||||
// Calculate the index of the last element
|
||||
int last = index(front + queSize - 1);
|
||||
return nums[last];
|
||||
}
|
||||
|
||||
/* Return array for printing */
|
||||
/* Return a vector for printing */
|
||||
vector<int> toVector() {
|
||||
// Elements enqueue
|
||||
// Copy only the elements in the occupied range
|
||||
vector<int> res(queSize);
|
||||
for (int i = 0, j = front; i < queSize; i++, j++) {
|
||||
res[i] = nums[index(j)];
|
||||
@@ -113,44 +113,44 @@ class ArrayDeque {
|
||||
}
|
||||
};
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Get the length of the double-ended queue */
|
||||
/* Initialize the deque */
|
||||
ArrayDeque *deque = new ArrayDeque(10);
|
||||
deque->pushLast(3);
|
||||
deque->pushLast(2);
|
||||
deque->pushLast(5);
|
||||
cout << "Double-ended queue deque = ";
|
||||
cout << "Deque deque = ";
|
||||
printVector(deque->toVector());
|
||||
|
||||
/* Update element */
|
||||
/* Access an element */
|
||||
int peekFirst = deque->peekFirst();
|
||||
cout << "Front element peekFirst = " << peekFirst << endl;
|
||||
int peekLast = deque->peekLast();
|
||||
cout << "Rear element peekLast = " << peekLast << endl;
|
||||
|
||||
/* Elements enqueue */
|
||||
/* Enqueue elements */
|
||||
deque->pushLast(4);
|
||||
cout << "After element 4 enqueues at rear, deque = ";
|
||||
cout << "After enqueuing element 4 at the rear, deque = ";
|
||||
printVector(deque->toVector());
|
||||
deque->pushFirst(1);
|
||||
cout << "After element 1 enqueues at front, deque = ";
|
||||
cout << "After enqueuing element 1 at the front, deque = ";
|
||||
printVector(deque->toVector());
|
||||
|
||||
/* Element dequeue */
|
||||
/* Dequeue an element */
|
||||
int popLast = deque->popLast();
|
||||
cout << "Rear dequeue element = " << popLast << ", after rear dequeue, deque = ";
|
||||
cout << "Element dequeued from the rear = " << popLast << ", after dequeuing from the rear, deque = ";
|
||||
printVector(deque->toVector());
|
||||
int popFirst = deque->popFirst();
|
||||
cout << "Front dequeue element = " << popFirst << ", after front dequeue, deque = ";
|
||||
cout << "Element dequeued from the front = " << popFirst << ", after dequeuing from the front, deque = ";
|
||||
printVector(deque->toVector());
|
||||
|
||||
/* Get the length of the double-ended queue */
|
||||
/* Get the deque size */
|
||||
int size = deque->size();
|
||||
cout << "Double-ended queue length size = " << size << endl;
|
||||
cout << "Deque size = " << size << endl;
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
/* Check whether the deque is empty */
|
||||
bool isEmpty = deque->isEmpty();
|
||||
cout << "Double-ended queue is empty = " << boolalpha << isEmpty << endl;
|
||||
cout << "Is the deque empty = " << boolalpha << isEmpty << endl;
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -6,17 +6,17 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Queue based on circular array implementation */
|
||||
/* Queue implemented with a circular array */
|
||||
class ArrayQueue {
|
||||
private:
|
||||
int *nums; // Array for storing queue elements
|
||||
int front; // Front pointer, points to the front of the queue element
|
||||
int queSize; // Queue length
|
||||
int *nums; // Array that stores the queue elements
|
||||
int front; // Front index, identifying the first element
|
||||
int queSize; // Queue size
|
||||
int queCapacity; // Queue capacity
|
||||
|
||||
public:
|
||||
ArrayQueue(int capacity) {
|
||||
// Initialize array
|
||||
// Initialize the array
|
||||
nums = new int[capacity];
|
||||
queCapacity = capacity;
|
||||
front = queSize = 0;
|
||||
@@ -26,17 +26,17 @@ class ArrayQueue {
|
||||
delete[] nums;
|
||||
}
|
||||
|
||||
/* Get the capacity of the queue */
|
||||
/* Get the queue capacity */
|
||||
int capacity() {
|
||||
return queCapacity;
|
||||
}
|
||||
|
||||
/* Get the length of the queue */
|
||||
/* Get the queue size */
|
||||
int size() {
|
||||
return queSize;
|
||||
}
|
||||
|
||||
/* Check if the queue is empty */
|
||||
/* Check whether the queue is empty */
|
||||
bool isEmpty() {
|
||||
return size() == 0;
|
||||
}
|
||||
@@ -47,10 +47,10 @@ class ArrayQueue {
|
||||
cout << "Queue is full" << endl;
|
||||
return;
|
||||
}
|
||||
// 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
|
||||
// Calculate the rear index, one position past the last element
|
||||
// Use modulo to wrap rear to the beginning when it passes the end of the array
|
||||
int rear = (front + queSize) % queCapacity;
|
||||
// Front pointer moves one position backward
|
||||
// Add num to the rear
|
||||
nums[rear] = num;
|
||||
queSize++;
|
||||
}
|
||||
@@ -58,22 +58,22 @@ class ArrayQueue {
|
||||
/* Dequeue */
|
||||
int pop() {
|
||||
int num = peek();
|
||||
// Move front pointer backward by one position, if it passes the tail, return to array head
|
||||
// Advance the front index by one position, wrapping to the beginning if it passes the end
|
||||
front = (front + 1) % queCapacity;
|
||||
queSize--;
|
||||
return num;
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
/* Access the front element */
|
||||
int peek() {
|
||||
if (isEmpty())
|
||||
throw out_of_range("Queue is empty");
|
||||
return nums[front];
|
||||
}
|
||||
|
||||
/* Convert array to Vector and return */
|
||||
/* Convert the array to a vector and return it */
|
||||
vector<int> toVector() {
|
||||
// Elements enqueue
|
||||
// Copy only the elements in the occupied range
|
||||
vector<int> arr(queSize);
|
||||
for (int i = 0, j = front; i < queSize; i++, j++) {
|
||||
arr[i] = nums[j % queCapacity];
|
||||
@@ -82,13 +82,13 @@ class ArrayQueue {
|
||||
}
|
||||
};
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Access front of the queue element */
|
||||
/* Initialize the queue */
|
||||
int capacity = 10;
|
||||
ArrayQueue *queue = new ArrayQueue(capacity);
|
||||
|
||||
/* Elements enqueue */
|
||||
/* Enqueue elements */
|
||||
queue->push(1);
|
||||
queue->push(3);
|
||||
queue->push(2);
|
||||
@@ -97,28 +97,28 @@ int main() {
|
||||
cout << "Queue queue = ";
|
||||
printVector(queue->toVector());
|
||||
|
||||
/* Return list for printing */
|
||||
/* Access the front element */
|
||||
int peek = queue->peek();
|
||||
cout << "Front element peek = " << peek << endl;
|
||||
|
||||
/* Element dequeue */
|
||||
/* Dequeue an element */
|
||||
peek = queue->pop();
|
||||
cout << "Dequeue element pop = " << peek << ", after dequeue, queue = ";
|
||||
cout << "Dequeued element pop = " << peek << "; after dequeueing, queue = ";
|
||||
printVector(queue->toVector());
|
||||
|
||||
/* Get the length of the queue */
|
||||
/* Get the queue size */
|
||||
int size = queue->size();
|
||||
cout << "Queue length size = " << size << endl;
|
||||
cout << "Queue size = " << size << endl;
|
||||
|
||||
/* Check if the queue is empty */
|
||||
/* Check whether the queue is empty */
|
||||
bool empty = queue->isEmpty();
|
||||
cout << "Queue is empty = " << empty << endl;
|
||||
cout << "Is the queue empty = " << empty << endl;
|
||||
|
||||
/* Test circular array */
|
||||
/* Test the circular array */
|
||||
for (int i = 0; i < 10; i++) {
|
||||
queue->push(i);
|
||||
queue->pop();
|
||||
cout << "After round " << i << " enqueue + dequeue, queue = ";
|
||||
cout << "Round " << i << " : after enqueue + dequeue, queue = ";
|
||||
printVector(queue->toVector());
|
||||
}
|
||||
|
||||
|
||||
@@ -6,18 +6,18 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Stack based on array implementation */
|
||||
/* Stack implemented with an array */
|
||||
class ArrayStack {
|
||||
private:
|
||||
vector<int> stack;
|
||||
|
||||
public:
|
||||
/* Get the length of the stack */
|
||||
/* Get the stack size */
|
||||
int size() {
|
||||
return stack.size();
|
||||
}
|
||||
|
||||
/* Check if the stack is empty */
|
||||
/* Check whether the stack is empty */
|
||||
bool isEmpty() {
|
||||
return stack.size() == 0;
|
||||
}
|
||||
@@ -34,25 +34,25 @@ class ArrayStack {
|
||||
return num;
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
/* Access the top element */
|
||||
int top() {
|
||||
if (isEmpty())
|
||||
throw out_of_range("Stack is empty");
|
||||
return stack.back();
|
||||
}
|
||||
|
||||
/* Return Vector */
|
||||
/* Return a vector */
|
||||
vector<int> toVector() {
|
||||
return stack;
|
||||
}
|
||||
};
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Access top of the stack element */
|
||||
/* Initialize the stack */
|
||||
ArrayStack *stack = new ArrayStack();
|
||||
|
||||
/* Elements push onto stack */
|
||||
/* Push elements onto the stack */
|
||||
stack->push(1);
|
||||
stack->push(3);
|
||||
stack->push(2);
|
||||
@@ -61,22 +61,22 @@ int main() {
|
||||
cout << "Stack stack = ";
|
||||
printVector(stack->toVector());
|
||||
|
||||
/* Return list for printing */
|
||||
/* Access the top element */
|
||||
int top = stack->top();
|
||||
cout << "Stack top element top = " << top << endl;
|
||||
cout << "Top element top = " << top << endl;
|
||||
|
||||
/* Element pop from stack */
|
||||
/* Pop an element from the stack */
|
||||
top = stack->pop();
|
||||
cout << "Pop element pop = " << top << ", after pop, stack = ";
|
||||
cout << "Popped element pop = " << top << "; after popping, stack = ";
|
||||
printVector(stack->toVector());
|
||||
|
||||
/* Get the length of the stack */
|
||||
/* Get the stack size */
|
||||
int size = stack->size();
|
||||
cout << "Stack length size = " << size << endl;
|
||||
cout << "Stack size = " << size << endl;
|
||||
|
||||
/* Check if empty */
|
||||
/* Check whether it is empty */
|
||||
bool empty = stack->isEmpty();
|
||||
cout << "Stack is empty = " << empty << endl;
|
||||
cout << "Is the stack empty = " << empty << endl;
|
||||
|
||||
// Free memory
|
||||
delete stack;
|
||||
|
||||
@@ -6,41 +6,41 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Get the length of the double-ended queue */
|
||||
/* Initialize the deque */
|
||||
deque<int> deque;
|
||||
|
||||
/* Elements enqueue */
|
||||
/* Enqueue elements */
|
||||
deque.push_back(2);
|
||||
deque.push_back(5);
|
||||
deque.push_back(4);
|
||||
deque.push_front(3);
|
||||
deque.push_front(1);
|
||||
cout << "Double-ended queue deque = ";
|
||||
cout << "Deque deque = ";
|
||||
printDeque(deque);
|
||||
|
||||
/* Update element */
|
||||
/* Access an element */
|
||||
int front = deque.front();
|
||||
cout << "Front element front = " << front << endl;
|
||||
int back = deque.back();
|
||||
cout << "Back element back = " << back << endl;
|
||||
cout << "Rear element back = " << back << endl;
|
||||
|
||||
/* Element dequeue */
|
||||
/* Dequeue an element */
|
||||
deque.pop_front();
|
||||
cout << "Front dequeue element popFront = " << front << ", after front dequeue, deque = ";
|
||||
cout << "Element removed from the front, popFront = " << front << ", after dequeuing from the front, deque = ";
|
||||
printDeque(deque);
|
||||
deque.pop_back();
|
||||
cout << "Rear dequeue element popLast = " << back << ", after rear dequeue, deque = ";
|
||||
cout << "Element removed from the rear, popLast = " << back << ", after dequeuing from the rear, deque = ";
|
||||
printDeque(deque);
|
||||
|
||||
/* Get the length of the double-ended queue */
|
||||
/* Get the deque size */
|
||||
int size = deque.size();
|
||||
cout << "Double-ended queue length size = " << size << endl;
|
||||
cout << "Deque size = " << size << endl;
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
/* Check whether the deque is empty */
|
||||
bool empty = deque.empty();
|
||||
cout << "Double-ended queue is empty = " << empty << endl;
|
||||
cout << "Is the deque empty = " << empty << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -9,17 +9,17 @@
|
||||
/* Doubly linked list node */
|
||||
struct DoublyListNode {
|
||||
int val; // Node value
|
||||
DoublyListNode *next; // Successor node pointer
|
||||
DoublyListNode *prev; // Predecessor node pointer
|
||||
DoublyListNode *next; // Pointer to the next node
|
||||
DoublyListNode *prev; // Pointer to the previous node
|
||||
DoublyListNode(int val) : val(val), prev(nullptr), next(nullptr) {
|
||||
}
|
||||
};
|
||||
|
||||
/* Double-ended queue based on doubly linked list implementation */
|
||||
/* Deque implemented with a doubly linked list */
|
||||
class LinkedListDeque {
|
||||
private:
|
||||
DoublyListNode *front, *rear; // Head node front, tail node rear
|
||||
int queSize = 0; // Length of the double-ended queue
|
||||
DoublyListNode *front, *rear; // Head node front and tail node rear
|
||||
int queSize = 0; // Deque size
|
||||
|
||||
public:
|
||||
/* Constructor */
|
||||
@@ -28,7 +28,7 @@ class LinkedListDeque {
|
||||
|
||||
/* Destructor */
|
||||
~LinkedListDeque() {
|
||||
// Traverse linked list to delete nodes and free memory
|
||||
// Traverse the linked list and delete each node to free its memory
|
||||
DoublyListNode *pre, *cur = front;
|
||||
while (cur != nullptr) {
|
||||
pre = cur;
|
||||
@@ -37,12 +37,12 @@ class LinkedListDeque {
|
||||
}
|
||||
}
|
||||
|
||||
/* Get the length of the double-ended queue */
|
||||
/* Get the deque size */
|
||||
int size() {
|
||||
return queSize;
|
||||
}
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
/* Check whether the deque is empty */
|
||||
bool isEmpty() {
|
||||
return size() == 0;
|
||||
}
|
||||
@@ -53,28 +53,28 @@ class LinkedListDeque {
|
||||
// If the linked list is empty, make both front and rear point to node
|
||||
if (isEmpty())
|
||||
front = rear = node;
|
||||
// Front of the queue enqueue operation
|
||||
// Enqueue at the front
|
||||
else if (isFront) {
|
||||
// Add node to the head of the linked list
|
||||
front->prev = node;
|
||||
node->next = front;
|
||||
front = node; // Update head node
|
||||
// Rear of the queue enqueue operation
|
||||
front = node; // Update the head node
|
||||
// Enqueue at the rear
|
||||
} else {
|
||||
// Add node to the tail of the linked list
|
||||
rear->next = node;
|
||||
node->prev = rear;
|
||||
rear = node; // Update tail node
|
||||
rear = node; // Update the tail node
|
||||
}
|
||||
queSize++; // Update queue length
|
||||
queSize++; // Update the deque size
|
||||
}
|
||||
|
||||
/* Front of the queue enqueue */
|
||||
/* Enqueue at the front */
|
||||
void pushFirst(int num) {
|
||||
push(num, true);
|
||||
}
|
||||
|
||||
/* Rear of the queue enqueue */
|
||||
/* Enqueue at the rear */
|
||||
void pushLast(int num) {
|
||||
push(num, false);
|
||||
}
|
||||
@@ -82,63 +82,63 @@ class LinkedListDeque {
|
||||
/* Dequeue operation */
|
||||
int pop(bool isFront) {
|
||||
if (isEmpty())
|
||||
throw out_of_range("Queue is empty");
|
||||
throw out_of_range("Deque is empty");
|
||||
int val;
|
||||
// When the deque has one element, front and rear point to the same node
|
||||
// When the deque size is 1, the head and tail point to the same node
|
||||
if (queSize == 1) {
|
||||
val = front->val;
|
||||
delete front; // Free the shared node once
|
||||
delete front; // Both point to the same node, so free it only once
|
||||
front = nullptr;
|
||||
rear = nullptr;
|
||||
}
|
||||
// Temporarily store head node value
|
||||
// Dequeue from the front
|
||||
else if (isFront) {
|
||||
val = front->val; // Delete head node
|
||||
// Delete head node
|
||||
val = front->val; // Save the head node value
|
||||
// Remove the head node
|
||||
DoublyListNode *fNext = front->next;
|
||||
fNext->prev = nullptr;
|
||||
front->next = nullptr;
|
||||
delete front;
|
||||
front = fNext; // Update head node
|
||||
// Temporarily store tail node value
|
||||
front = fNext; // Update the head node
|
||||
// Dequeue from the rear
|
||||
} else {
|
||||
val = rear->val; // Delete tail node
|
||||
// Update tail node
|
||||
val = rear->val; // Save the tail node value
|
||||
// Remove the tail node
|
||||
DoublyListNode *rPrev = rear->prev;
|
||||
rPrev->next = nullptr;
|
||||
rear->prev = nullptr;
|
||||
delete rear;
|
||||
rear = rPrev; // Update tail node
|
||||
rear = rPrev; // Update the tail node
|
||||
}
|
||||
queSize--; // Update queue length
|
||||
queSize--; // Update the deque size
|
||||
return val;
|
||||
}
|
||||
|
||||
/* Rear of the queue dequeue */
|
||||
/* Dequeue from the front */
|
||||
int popFirst() {
|
||||
return pop(true);
|
||||
}
|
||||
|
||||
/* Access rear of the queue element */
|
||||
/* Dequeue from the rear */
|
||||
int popLast() {
|
||||
return pop(false);
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
/* Access the front element */
|
||||
int peekFirst() {
|
||||
if (isEmpty())
|
||||
throw out_of_range("Deque is empty");
|
||||
return front->val;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Access the rear element */
|
||||
int peekLast() {
|
||||
if (isEmpty())
|
||||
throw out_of_range("Deque is empty");
|
||||
return rear->val;
|
||||
}
|
||||
|
||||
/* Return array for printing */
|
||||
/* Return a vector for printing */
|
||||
vector<int> toVector() {
|
||||
DoublyListNode *node = front;
|
||||
vector<int> res(size());
|
||||
@@ -150,45 +150,45 @@ class LinkedListDeque {
|
||||
}
|
||||
};
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Get the length of the double-ended queue */
|
||||
/* Initialize the deque */
|
||||
LinkedListDeque *deque = new LinkedListDeque();
|
||||
deque->pushLast(3);
|
||||
deque->pushLast(2);
|
||||
deque->pushLast(5);
|
||||
cout << "Double-ended queue deque = ";
|
||||
cout << "Deque deque = ";
|
||||
printVector(deque->toVector());
|
||||
|
||||
/* Update element */
|
||||
/* Access an element */
|
||||
int peekFirst = deque->peekFirst();
|
||||
cout << "Front element peekFirst = " << peekFirst << endl;
|
||||
int peekLast = deque->peekLast();
|
||||
cout << "Rear element peekLast = " << peekLast << endl;
|
||||
|
||||
/* Elements enqueue */
|
||||
/* Enqueue elements */
|
||||
deque->pushLast(4);
|
||||
cout << "After element 4 enqueues at back, deque =";
|
||||
cout << "After enqueuing element 4 at the rear, deque =";
|
||||
printVector(deque->toVector());
|
||||
deque->pushFirst(1);
|
||||
cout << "After element 1 enqueues at front, deque = ";
|
||||
cout << "After enqueuing element 1 at the front, deque = ";
|
||||
printVector(deque->toVector());
|
||||
|
||||
/* Element dequeue */
|
||||
/* Dequeue an element */
|
||||
int popLast = deque->popLast();
|
||||
cout << "Rear dequeue element = " << popLast << ", after rear dequeue, deque = ";
|
||||
cout << "Element dequeued from the rear = " << popLast << ", after dequeuing from the rear, deque = ";
|
||||
printVector(deque->toVector());
|
||||
int popFirst = deque->popFirst();
|
||||
cout << "Front dequeue element = " << popFirst << ", after front dequeue, deque = ";
|
||||
cout << "Element dequeued from the front = " << popFirst << ", after dequeuing from the front, deque = ";
|
||||
printVector(deque->toVector());
|
||||
|
||||
/* Get the length of the double-ended queue */
|
||||
/* Get the deque size */
|
||||
int size = deque->size();
|
||||
cout << "Double-ended queue length size = " << size << endl;
|
||||
cout << "Deque size = " << size << endl;
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
/* Check whether the deque is empty */
|
||||
bool isEmpty = deque->isEmpty();
|
||||
cout << "Double-ended queue is empty = " << boolalpha << isEmpty << endl;
|
||||
cout << "Is the deque empty = " << boolalpha << isEmpty << endl;
|
||||
|
||||
// Free memory
|
||||
delete deque;
|
||||
|
||||
@@ -6,10 +6,10 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Queue based on linked list implementation */
|
||||
/* Queue implemented with a linked list */
|
||||
class LinkedListQueue {
|
||||
private:
|
||||
ListNode *front, *rear; // Head node front, tail node rear
|
||||
ListNode *front, *rear; // Head node front and tail node rear
|
||||
int queSize;
|
||||
|
||||
public:
|
||||
@@ -20,16 +20,16 @@ class LinkedListQueue {
|
||||
}
|
||||
|
||||
~LinkedListQueue() {
|
||||
// Traverse linked list to delete nodes and free memory
|
||||
// Traverse the linked list and delete each node to free its memory
|
||||
freeMemoryLinkedList(front);
|
||||
}
|
||||
|
||||
/* Get the length of the queue */
|
||||
/* Get the queue size */
|
||||
int size() {
|
||||
return queSize;
|
||||
}
|
||||
|
||||
/* Check if the queue is empty */
|
||||
/* Check whether the queue is empty */
|
||||
bool isEmpty() {
|
||||
return queSize == 0;
|
||||
}
|
||||
@@ -38,12 +38,12 @@ class LinkedListQueue {
|
||||
void push(int num) {
|
||||
// Add num after the tail node
|
||||
ListNode *node = new ListNode(num);
|
||||
// If the queue is empty, make both front and rear point to the node
|
||||
// If the queue is empty, make both the head and tail point to this node
|
||||
if (front == nullptr) {
|
||||
front = node;
|
||||
rear = node;
|
||||
}
|
||||
// If the queue is not empty, add the node after the tail node
|
||||
// If the queue is not empty, add this node after the tail node
|
||||
else {
|
||||
rear->next = node;
|
||||
rear = node;
|
||||
@@ -54,7 +54,7 @@ class LinkedListQueue {
|
||||
/* Dequeue */
|
||||
int pop() {
|
||||
int num = peek();
|
||||
// Delete head node
|
||||
// Remove the head node
|
||||
ListNode *tmp = front;
|
||||
front = front->next;
|
||||
// Free memory
|
||||
@@ -63,14 +63,14 @@ class LinkedListQueue {
|
||||
return num;
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
/* Access the front element */
|
||||
int peek() {
|
||||
if (size() == 0)
|
||||
throw out_of_range("Queue is empty");
|
||||
return front->val;
|
||||
}
|
||||
|
||||
/* Convert linked list to Vector and return */
|
||||
/* Convert the linked list to a vector and return it */
|
||||
vector<int> toVector() {
|
||||
ListNode *node = front;
|
||||
vector<int> res(size());
|
||||
@@ -82,12 +82,12 @@ class LinkedListQueue {
|
||||
}
|
||||
};
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Access front of the queue element */
|
||||
/* Initialize the queue */
|
||||
LinkedListQueue *queue = new LinkedListQueue();
|
||||
|
||||
/* Elements enqueue */
|
||||
/* Enqueue elements */
|
||||
queue->push(1);
|
||||
queue->push(3);
|
||||
queue->push(2);
|
||||
@@ -96,22 +96,22 @@ int main() {
|
||||
cout << "Queue queue = ";
|
||||
printVector(queue->toVector());
|
||||
|
||||
/* Return list for printing */
|
||||
/* Access the front element */
|
||||
int peek = queue->peek();
|
||||
cout << "Front element peek = " << peek << endl;
|
||||
|
||||
/* Element dequeue */
|
||||
/* Dequeue an element */
|
||||
peek = queue->pop();
|
||||
cout << "Dequeue element pop = " << peek << ", after dequeue, queue = ";
|
||||
cout << "Dequeued element pop = " << peek << "; after dequeueing, queue = ";
|
||||
printVector(queue->toVector());
|
||||
|
||||
/* Get the length of the queue */
|
||||
/* Get the queue size */
|
||||
int size = queue->size();
|
||||
cout << "Queue length size = " << size << endl;
|
||||
cout << "Queue size = " << size << endl;
|
||||
|
||||
/* Check if the queue is empty */
|
||||
/* Check whether the queue is empty */
|
||||
bool empty = queue->isEmpty();
|
||||
cout << "Queue is empty = " << empty << endl;
|
||||
cout << "Is the queue empty = " << empty << endl;
|
||||
|
||||
// Free memory
|
||||
delete queue;
|
||||
|
||||
@@ -6,11 +6,11 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Stack based on linked list implementation */
|
||||
/* Stack implemented with a linked list */
|
||||
class LinkedListStack {
|
||||
private:
|
||||
ListNode *stackTop; // Use head node as stack top
|
||||
int stkSize; // Stack length
|
||||
ListNode *stackTop; // Use the head node as the stack top
|
||||
int stkSize; // Stack size
|
||||
|
||||
public:
|
||||
LinkedListStack() {
|
||||
@@ -19,16 +19,16 @@ class LinkedListStack {
|
||||
}
|
||||
|
||||
~LinkedListStack() {
|
||||
// Traverse linked list to delete nodes and free memory
|
||||
// Traverse the linked list and delete each node to free its memory
|
||||
freeMemoryLinkedList(stackTop);
|
||||
}
|
||||
|
||||
/* Get the length of the stack */
|
||||
/* Get the stack size */
|
||||
int size() {
|
||||
return stkSize;
|
||||
}
|
||||
|
||||
/* Check if the stack is empty */
|
||||
/* Check whether the stack is empty */
|
||||
bool isEmpty() {
|
||||
return size() == 0;
|
||||
}
|
||||
@@ -52,14 +52,14 @@ class LinkedListStack {
|
||||
return num;
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
/* Access the top element */
|
||||
int top() {
|
||||
if (isEmpty())
|
||||
throw out_of_range("Stack is empty");
|
||||
return stackTop->val;
|
||||
}
|
||||
|
||||
/* Convert List to Array and return */
|
||||
/* Convert the linked list to a vector and return it */
|
||||
vector<int> toVector() {
|
||||
ListNode *node = stackTop;
|
||||
vector<int> res(size());
|
||||
@@ -71,12 +71,12 @@ class LinkedListStack {
|
||||
}
|
||||
};
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Access top of the stack element */
|
||||
/* Initialize the stack */
|
||||
LinkedListStack *stack = new LinkedListStack();
|
||||
|
||||
/* Elements push onto stack */
|
||||
/* Push elements onto the stack */
|
||||
stack->push(1);
|
||||
stack->push(3);
|
||||
stack->push(2);
|
||||
@@ -85,22 +85,22 @@ int main() {
|
||||
cout << "Stack stack = ";
|
||||
printVector(stack->toVector());
|
||||
|
||||
/* Return list for printing */
|
||||
/* Access the top element */
|
||||
int top = stack->top();
|
||||
cout << "Stack top element top = " << top << endl;
|
||||
cout << "Top element top = " << top << endl;
|
||||
|
||||
/* Element pop from stack */
|
||||
/* Pop an element from the stack */
|
||||
top = stack->pop();
|
||||
cout << "Pop element pop = " << top << ", after pop, stack = ";
|
||||
cout << "Popped element pop = " << top << "; after popping, stack = ";
|
||||
printVector(stack->toVector());
|
||||
|
||||
/* Get the length of the stack */
|
||||
/* Get the stack size */
|
||||
int size = stack->size();
|
||||
cout << "Stack length size = " << size << endl;
|
||||
cout << "Stack size = " << size << endl;
|
||||
|
||||
/* Check if empty */
|
||||
/* Check whether it is empty */
|
||||
bool empty = stack->isEmpty();
|
||||
cout << "Stack is empty = " << empty << endl;
|
||||
cout << "Is the stack empty = " << empty << endl;
|
||||
|
||||
// Free memory
|
||||
delete stack;
|
||||
|
||||
@@ -6,12 +6,12 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Access front of the queue element */
|
||||
/* Initialize the queue */
|
||||
queue<int> queue;
|
||||
|
||||
/* Elements enqueue */
|
||||
/* Enqueue elements */
|
||||
queue.push(1);
|
||||
queue.push(3);
|
||||
queue.push(2);
|
||||
@@ -20,22 +20,22 @@ int main() {
|
||||
cout << "Queue queue = ";
|
||||
printQueue(queue);
|
||||
|
||||
/* Return list for printing */
|
||||
/* Access the front element */
|
||||
int front = queue.front();
|
||||
cout << "Front element front = " << front << endl;
|
||||
|
||||
/* Element dequeue */
|
||||
/* Dequeue an element */
|
||||
queue.pop();
|
||||
cout << "Dequeue element front = " << front << ", after dequeue, queue = ";
|
||||
cout << "Dequeued element front = " << front << "; after dequeueing, queue = ";
|
||||
printQueue(queue);
|
||||
|
||||
/* Get the length of the queue */
|
||||
/* Get the queue size */
|
||||
int size = queue.size();
|
||||
cout << "Queue length size = " << size << endl;
|
||||
cout << "Queue size = " << size << endl;
|
||||
|
||||
/* Check if the queue is empty */
|
||||
/* Check whether the queue is empty */
|
||||
bool empty = queue.empty();
|
||||
cout << "Queue is empty = " << empty << endl;
|
||||
cout << "Is the queue empty = " << empty << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -6,12 +6,12 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Access top of the stack element */
|
||||
/* Initialize the stack */
|
||||
stack<int> stack;
|
||||
|
||||
/* Elements push onto stack */
|
||||
/* Push elements onto the stack */
|
||||
stack.push(1);
|
||||
stack.push(3);
|
||||
stack.push(2);
|
||||
@@ -20,22 +20,22 @@ int main() {
|
||||
cout << "Stack stack = ";
|
||||
printStack(stack);
|
||||
|
||||
/* Return list for printing */
|
||||
/* Access the top element */
|
||||
int top = stack.top();
|
||||
cout << "Stack top element top = " << top << endl;
|
||||
cout << "Top element top = " << top << endl;
|
||||
|
||||
/* Element pop from stack */
|
||||
/* Pop an element from the stack */
|
||||
stack.pop(); // No return value
|
||||
cout << "Pop element pop = " << top << ", after pop, stack = ";
|
||||
cout << "Popped element pop = " << top << "; after popping, stack = ";
|
||||
printStack(stack);
|
||||
|
||||
/* Get the length of the stack */
|
||||
/* Get the stack size */
|
||||
int size = stack.size();
|
||||
cout << "Stack length size = " << size << endl;
|
||||
cout << "Stack size = " << size << endl;
|
||||
|
||||
/* Check if empty */
|
||||
/* Check whether it is empty */
|
||||
bool empty = stack.empty();
|
||||
cout << "Stack is empty = " << empty << endl;
|
||||
cout << "Is the stack empty = " << empty << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Binary tree class represented by array */
|
||||
/* Binary tree class using an array representation */
|
||||
class ArrayBinaryTree {
|
||||
public:
|
||||
/* Constructor */
|
||||
@@ -14,30 +14,30 @@ class ArrayBinaryTree {
|
||||
tree = arr;
|
||||
}
|
||||
|
||||
/* List capacity */
|
||||
/* Number of positions in the array */
|
||||
int size() {
|
||||
return tree.size();
|
||||
}
|
||||
|
||||
/* Get value of node at index i */
|
||||
/* Get the value of the node at index i */
|
||||
int val(int i) {
|
||||
// Return INT_MAX if index out of bounds, representing empty position
|
||||
// If the index is out of bounds, return INT_MAX to represent an empty position
|
||||
if (i < 0 || i >= size())
|
||||
return INT_MAX;
|
||||
return tree[i];
|
||||
}
|
||||
|
||||
/* Get index of left child node of node at index i */
|
||||
/* Get the left child index of the node at index i */
|
||||
int left(int i) {
|
||||
return 2 * i + 1;
|
||||
}
|
||||
|
||||
/* Get index of right child node of node at index i */
|
||||
/* Get the right child index of the node at index i */
|
||||
int right(int i) {
|
||||
return 2 * i + 2;
|
||||
}
|
||||
|
||||
/* Get index of parent node of node at index i */
|
||||
/* Get the parent index of the 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 directly
|
||||
// Traverse the array directly
|
||||
for (int i = 0; i < size(); i++) {
|
||||
if (val(i) != INT_MAX)
|
||||
res.push_back(val(i));
|
||||
@@ -79,7 +79,7 @@ class ArrayBinaryTree {
|
||||
|
||||
/* Depth-first traversal */
|
||||
void dfs(int i, string order, vector<int> &res) {
|
||||
// If empty position, return
|
||||
// Return if this position is empty
|
||||
if (val(i) == INT_MAX)
|
||||
return;
|
||||
// Preorder traversal
|
||||
@@ -96,41 +96,41 @@ class ArrayBinaryTree {
|
||||
}
|
||||
};
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
// Initialize binary tree
|
||||
// Use INT_MAX to represent empty position nullptr
|
||||
// Initialize the binary tree
|
||||
// Use INT_MAX to represent an 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 << "Array representation of binary tree:\n";
|
||||
cout << "\nInitialize the binary tree\n";
|
||||
cout << "Array representation of the binary tree:\n";
|
||||
printVector(arr);
|
||||
cout << "Linked list representation of binary tree:\n";
|
||||
cout << "Linked representation of the binary tree:\n";
|
||||
printTree(root);
|
||||
|
||||
// Binary tree class represented by array
|
||||
// Binary tree class using an array representation
|
||||
ArrayBinaryTree abt(arr);
|
||||
|
||||
// Access node
|
||||
// Access a node
|
||||
int i = 1;
|
||||
int l = abt.left(i), r = abt.right(i), p = abt.parent(i);
|
||||
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";
|
||||
cout << "\nCurrent node index: " << i << ", value: " << abt.val(i) << "\n";
|
||||
cout << "Left child index: " << l << ", value: " << (abt.val(l) != INT_MAX ? to_string(abt.val(l)) : "nullptr") << "\n";
|
||||
cout << "Right child index: " << r << ", value: " << (abt.val(r) != INT_MAX ? to_string(abt.val(r)) : "nullptr") << "\n";
|
||||
cout << "Parent index: " << p << ", value: " << (abt.val(p) != INT_MAX ? to_string(abt.val(p)) : "nullptr") << "\n";
|
||||
|
||||
// Traverse tree
|
||||
// Traverse the tree
|
||||
vector<int> res = abt.levelOrder();
|
||||
cout << "\nLevel-order traversal: ";
|
||||
printVector(res);
|
||||
res = abt.preOrder();
|
||||
cout << "Pre-order traversal: ";
|
||||
cout << "Preorder traversal: ";
|
||||
printVector(res);
|
||||
res = abt.inOrder();
|
||||
cout << "In-order traversal: ";
|
||||
cout << "Inorder traversal: ";
|
||||
printVector(res);
|
||||
res = abt.postOrder();
|
||||
cout << "Post-order traversal: ";
|
||||
cout << "Postorder traversal: ";
|
||||
printVector(res);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -9,93 +9,93 @@
|
||||
/* AVL tree */
|
||||
class AVLTree {
|
||||
private:
|
||||
/* Update node height */
|
||||
/* Update the node height */
|
||||
void updateHeight(TreeNode *node) {
|
||||
// Node height equals the height of the tallest subtree + 1
|
||||
// The node height equals the height of its taller subtree + 1
|
||||
node->height = max(height(node->left), height(node->right)) + 1;
|
||||
}
|
||||
|
||||
/* Right rotation operation */
|
||||
/* Right rotation */
|
||||
TreeNode *rightRotate(TreeNode *node) {
|
||||
TreeNode *child = node->left;
|
||||
TreeNode *grandChild = child->right;
|
||||
// Using child as pivot, rotate node to the right
|
||||
// Rotate node to the right around child
|
||||
child->right = node;
|
||||
node->left = grandChild;
|
||||
// Update node height
|
||||
// Update the node height
|
||||
updateHeight(node);
|
||||
updateHeight(child);
|
||||
// Return root node of subtree after rotation
|
||||
// Return the root of the rotated subtree
|
||||
return child;
|
||||
}
|
||||
|
||||
/* Left rotation operation */
|
||||
/* Left rotation */
|
||||
TreeNode *leftRotate(TreeNode *node) {
|
||||
TreeNode *child = node->right;
|
||||
TreeNode *grandChild = child->left;
|
||||
// Using child as pivot, rotate node to the left
|
||||
// Rotate node to the left around child
|
||||
child->left = node;
|
||||
node->right = grandChild;
|
||||
// Update node height
|
||||
// Update the node height
|
||||
updateHeight(node);
|
||||
updateHeight(child);
|
||||
// Return root node of subtree after rotation
|
||||
// Return the root of the rotated subtree
|
||||
return child;
|
||||
}
|
||||
|
||||
/* Perform rotation operation to restore balance to this subtree */
|
||||
/* Perform rotations to restore balance in this subtree */
|
||||
TreeNode *rotate(TreeNode *node) {
|
||||
// Get balance factor of node
|
||||
// Get the balance factor of node
|
||||
int _balanceFactor = balanceFactor(node);
|
||||
// Left-leaning tree
|
||||
// Left-heavy tree
|
||||
if (_balanceFactor > 1) {
|
||||
if (balanceFactor(node->left) >= 0) {
|
||||
// Right rotation
|
||||
// Rotate right
|
||||
return rightRotate(node);
|
||||
} else {
|
||||
// First left rotation then right rotation
|
||||
// Rotate left, then right
|
||||
node->left = leftRotate(node->left);
|
||||
return rightRotate(node);
|
||||
}
|
||||
}
|
||||
// Right-leaning tree
|
||||
// Right-heavy tree
|
||||
if (_balanceFactor < -1) {
|
||||
if (balanceFactor(node->right) <= 0) {
|
||||
// Left rotation
|
||||
// Rotate left
|
||||
return leftRotate(node);
|
||||
} else {
|
||||
// First right rotation then left rotation
|
||||
// Rotate right, then left
|
||||
node->right = rightRotate(node->right);
|
||||
return leftRotate(node);
|
||||
}
|
||||
}
|
||||
// Balanced tree, no rotation needed, return directly
|
||||
// The tree is balanced; return without rotating
|
||||
return node;
|
||||
}
|
||||
|
||||
/* Recursively insert node (helper method) */
|
||||
/* Insert a node recursively (helper method) */
|
||||
TreeNode *insertHelper(TreeNode *node, int val) {
|
||||
if (node == nullptr)
|
||||
return new TreeNode(val);
|
||||
/* 1. Find insertion position and insert node */
|
||||
/* 1. Find the insertion position and insert the node */
|
||||
if (val < node->val)
|
||||
node->left = insertHelper(node->left, val);
|
||||
else if (val > node->val)
|
||||
node->right = insertHelper(node->right, val);
|
||||
else
|
||||
return node; // Duplicate node not inserted, return directly
|
||||
updateHeight(node); // Update node height
|
||||
/* 2. Perform rotation operation to restore balance to this subtree */
|
||||
return node; // Return without inserting a duplicate node
|
||||
updateHeight(node); // Update the node height
|
||||
/* 2. Perform rotations to restore balance in this subtree */
|
||||
node = rotate(node);
|
||||
// Return root node of subtree
|
||||
// Return the root of the subtree
|
||||
return node;
|
||||
}
|
||||
|
||||
/* Recursively delete node (helper method) */
|
||||
/* Remove a node recursively (helper method) */
|
||||
TreeNode *removeHelper(TreeNode *node, int val) {
|
||||
if (node == nullptr)
|
||||
return nullptr;
|
||||
/* 1. Find node and delete */
|
||||
/* 1. Find and remove the node */
|
||||
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, delete node directly and return
|
||||
// Number of children = 0: remove node and return
|
||||
if (child == nullptr) {
|
||||
delete node;
|
||||
return nullptr;
|
||||
}
|
||||
// Number of child nodes = 1, delete node directly
|
||||
// Number of children = 1: remove node directly
|
||||
else {
|
||||
delete node;
|
||||
node = child;
|
||||
}
|
||||
} else {
|
||||
// Number of child nodes = 2, delete the next node in inorder traversal and replace current node with it
|
||||
// Number of children = 2: remove the inorder successor and use its value to replace the current node value
|
||||
TreeNode *temp = node->right;
|
||||
while (temp->left != nullptr) {
|
||||
temp = temp->left;
|
||||
@@ -124,57 +124,57 @@ class AVLTree {
|
||||
node->val = tempVal;
|
||||
}
|
||||
}
|
||||
updateHeight(node); // Update node height
|
||||
/* 2. Perform rotation operation to restore balance to this subtree */
|
||||
updateHeight(node); // Update the node height
|
||||
/* 2. Perform rotations to restore balance in this subtree */
|
||||
node = rotate(node);
|
||||
// Return root node of subtree
|
||||
// Return the root of the subtree
|
||||
return node;
|
||||
}
|
||||
|
||||
public:
|
||||
TreeNode *root; // Root node
|
||||
|
||||
/* Get node height */
|
||||
/* Get the node height */
|
||||
int height(TreeNode *node) {
|
||||
// Empty node height is -1, leaf node height is 0
|
||||
// A null node has height -1; a leaf has height 0
|
||||
return node == nullptr ? -1 : node->height;
|
||||
}
|
||||
|
||||
/* Get balance factor */
|
||||
/* Get the balance factor */
|
||||
int balanceFactor(TreeNode *node) {
|
||||
// Empty node balance factor is 0
|
||||
// A null node has balance factor 0
|
||||
if (node == nullptr)
|
||||
return 0;
|
||||
// Node balance factor = left subtree height - right subtree height
|
||||
return height(node->left) - height(node->right);
|
||||
}
|
||||
|
||||
/* Insert node */
|
||||
/* Insert a node */
|
||||
void insert(int val) {
|
||||
root = insertHelper(root, val);
|
||||
}
|
||||
|
||||
/* Remove node */
|
||||
/* Remove a node */
|
||||
void remove(int val) {
|
||||
root = removeHelper(root, val);
|
||||
}
|
||||
|
||||
/* Search node */
|
||||
/* Find a node */
|
||||
TreeNode *search(int val) {
|
||||
TreeNode *cur = root;
|
||||
// Loop search, exit after passing leaf node
|
||||
// Continue searching while the current node pointer is not null
|
||||
while (cur != nullptr) {
|
||||
// Target node is in cur's right subtree
|
||||
// The target node lies in the right subtree of cur
|
||||
if (cur->val < val)
|
||||
cur = cur->right;
|
||||
// Target node is in cur's left subtree
|
||||
// The target node lies in the left subtree of cur
|
||||
else if (cur->val > val)
|
||||
cur = cur->left;
|
||||
// Found target node, exit loop
|
||||
// The target node was found; exit the loop
|
||||
else
|
||||
break;
|
||||
}
|
||||
// Return target node
|
||||
// Return the target node, or nullptr if it was not found
|
||||
return cur;
|
||||
}
|
||||
|
||||
@@ -190,23 +190,23 @@ class AVLTree {
|
||||
|
||||
void testInsert(AVLTree &tree, int val) {
|
||||
tree.insert(val);
|
||||
cout << "\nAfter inserting node " << val << ", AVL tree is" << endl;
|
||||
cout << "\nAfter inserting node " << val << " , the AVL tree is" << endl;
|
||||
printTree(tree.root);
|
||||
}
|
||||
|
||||
void testRemove(AVLTree &tree, int val) {
|
||||
tree.remove(val);
|
||||
cout << "\nAfter removing node " << val << ", AVL tree is" << endl;
|
||||
cout << "\nAfter removing node " << val << " , the AVL tree is" << endl;
|
||||
printTree(tree.root);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Please pay attention to how the AVL tree maintains balance after inserting nodes */
|
||||
/* Initialize an empty AVL tree */
|
||||
AVLTree avlTree;
|
||||
|
||||
/* Insert node */
|
||||
// Delete nodes
|
||||
/* Insert a node */
|
||||
// Observe how the AVL tree maintains balance after a node is inserted
|
||||
testInsert(avlTree, 1);
|
||||
testInsert(avlTree, 2);
|
||||
testInsert(avlTree, 3);
|
||||
@@ -218,16 +218,16 @@ int main() {
|
||||
testInsert(avlTree, 10);
|
||||
testInsert(avlTree, 6);
|
||||
|
||||
/* Please pay attention to how the AVL tree maintains balance after deleting nodes */
|
||||
/* Insert a duplicate node */
|
||||
testInsert(avlTree, 7);
|
||||
|
||||
/* Remove node */
|
||||
// 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
|
||||
/* Remove a node */
|
||||
// Observe how the AVL tree maintains balance after a node is removed
|
||||
testRemove(avlTree, 8); // Remove a node with 0 children
|
||||
testRemove(avlTree, 5); // Remove a node with 1 child
|
||||
testRemove(avlTree, 4); // Remove a node with 2 children
|
||||
|
||||
/* Search node */
|
||||
/* Look up a node */
|
||||
TreeNode *node = avlTree.search(7);
|
||||
cout << "\nFound node object is " << node << ", node value = " << node->val << endl;
|
||||
cout << "\nFound node address: " << node << ", node value = " << node->val << endl;
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ class BinarySearchTree {
|
||||
public:
|
||||
/* Constructor */
|
||||
BinarySearchTree() {
|
||||
// Initialize empty tree
|
||||
// Initialize an empty tree
|
||||
root = nullptr;
|
||||
}
|
||||
|
||||
@@ -23,52 +23,52 @@ class BinarySearchTree {
|
||||
freeMemoryTree(root);
|
||||
}
|
||||
|
||||
/* Get binary tree root node */
|
||||
/* Get the root of the binary tree */
|
||||
TreeNode *getRoot() {
|
||||
return root;
|
||||
}
|
||||
|
||||
/* Search node */
|
||||
/* Find a node */
|
||||
TreeNode *search(int num) {
|
||||
TreeNode *cur = root;
|
||||
// Loop search, exit after passing leaf node
|
||||
// Continue searching while the current node pointer is not null
|
||||
while (cur != nullptr) {
|
||||
// Target node is in cur's right subtree
|
||||
// The target node lies in the right subtree of cur
|
||||
if (cur->val < num)
|
||||
cur = cur->right;
|
||||
// Target node is in cur's left subtree
|
||||
// The target node lies in the left subtree of cur
|
||||
else if (cur->val > num)
|
||||
cur = cur->left;
|
||||
// Found target node, exit loop
|
||||
// The target node was found; exit the loop
|
||||
else
|
||||
break;
|
||||
}
|
||||
// Return target node
|
||||
// Return the target node, or nullptr if it was not found
|
||||
return cur;
|
||||
}
|
||||
|
||||
/* Insert node */
|
||||
/* Insert a node */
|
||||
void insert(int num) {
|
||||
// If tree is empty, initialize root node
|
||||
// If the tree is empty, initialize the root node
|
||||
if (root == nullptr) {
|
||||
root = new TreeNode(num);
|
||||
return;
|
||||
}
|
||||
TreeNode *cur = root, *pre = nullptr;
|
||||
// Loop search, exit after passing leaf node
|
||||
// Continue searching while the current node pointer is not null
|
||||
while (cur != nullptr) {
|
||||
// Found duplicate node, return directly
|
||||
// Return immediately if a duplicate node is found
|
||||
if (cur->val == num)
|
||||
return;
|
||||
pre = cur;
|
||||
// Insertion position is in cur's right subtree
|
||||
// The insertion position lies in the right subtree of cur
|
||||
if (cur->val < num)
|
||||
cur = cur->right;
|
||||
// Insertion position is in cur's left subtree
|
||||
// The insertion position lies in the left subtree of cur
|
||||
else
|
||||
cur = cur->left;
|
||||
}
|
||||
// Insert node
|
||||
// Insert a node
|
||||
TreeNode *node = new TreeNode(num);
|
||||
if (pre->val < num)
|
||||
pre->right = node;
|
||||
@@ -76,91 +76,91 @@ class BinarySearchTree {
|
||||
pre->left = node;
|
||||
}
|
||||
|
||||
/* Remove node */
|
||||
/* Remove a node */
|
||||
void remove(int num) {
|
||||
// If tree is empty, return directly
|
||||
// Return immediately if the tree is empty
|
||||
if (root == nullptr)
|
||||
return;
|
||||
TreeNode *cur = root, *pre = nullptr;
|
||||
// Loop search, exit after passing leaf node
|
||||
// Continue searching while the current node pointer is not null
|
||||
while (cur != nullptr) {
|
||||
// Found node to delete, exit loop
|
||||
// The node to remove was found; exit the loop
|
||||
if (cur->val == num)
|
||||
break;
|
||||
pre = cur;
|
||||
// Node to delete is in cur's right subtree
|
||||
// The node to remove lies in the right subtree of cur
|
||||
if (cur->val < num)
|
||||
cur = cur->right;
|
||||
// Node to delete is in cur's left subtree
|
||||
// The node to remove lies in the left subtree of cur
|
||||
else
|
||||
cur = cur->left;
|
||||
}
|
||||
// If no node to delete, return directly
|
||||
// Return immediately if the node to remove does not exist
|
||||
if (cur == nullptr)
|
||||
return;
|
||||
// Number of child nodes = 0 or 1
|
||||
// Number of children = 0 or 1
|
||||
if (cur->left == nullptr || cur->right == nullptr) {
|
||||
// When number of child nodes = 0 / 1, child = nullptr / that child node
|
||||
// With 0 or 1 child, child is nullptr or that child, respectively
|
||||
TreeNode *child = cur->left != nullptr ? cur->left : cur->right;
|
||||
// Delete node cur
|
||||
// Remove node cur
|
||||
if (cur != root) {
|
||||
if (pre->left == cur)
|
||||
pre->left = child;
|
||||
else
|
||||
pre->right = child;
|
||||
} else {
|
||||
// If deleted node is root node, reassign root node
|
||||
// If the removed node is the root, assign the new root
|
||||
root = child;
|
||||
}
|
||||
// Free memory
|
||||
delete cur;
|
||||
}
|
||||
// Number of child nodes = 2
|
||||
// Number of children = 2
|
||||
else {
|
||||
// Get next node of cur in inorder traversal
|
||||
// Get the inorder successor of cur
|
||||
TreeNode *tmp = cur->right;
|
||||
while (tmp->left != nullptr) {
|
||||
tmp = tmp->left;
|
||||
}
|
||||
int tmpVal = tmp->val;
|
||||
// Recursively delete node tmp
|
||||
// Recursively remove node tmp
|
||||
remove(tmp->val);
|
||||
// Replace cur with tmp
|
||||
// Replace the value of cur with the value of tmp
|
||||
cur->val = tmpVal;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Initialize binary search tree */
|
||||
/* Initialize the binary search tree */
|
||||
BinarySearchTree *bst = new BinarySearchTree();
|
||||
// Please note that different insertion orders will generate different binary trees, this sequence can generate a perfect binary tree
|
||||
// Different insertion orders produce different binary trees; this sequence produces 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 << "Initialized binary tree is\n" << endl;
|
||||
cout << endl << "Binary tree after initialization:\n" << endl;
|
||||
printTree(bst->getRoot());
|
||||
|
||||
/* Search node */
|
||||
/* Find a node */
|
||||
TreeNode *node = bst->search(7);
|
||||
cout << endl << "Found node object is " << node << ", node value = " << node->val << endl;
|
||||
cout << endl << "Found node address: " << node << ", node value = " << node->val << endl;
|
||||
|
||||
/* Insert node */
|
||||
/* Insert a node */
|
||||
bst->insert(16);
|
||||
cout << endl << "After inserting node 16, binary tree is\n" << endl;
|
||||
cout << endl << "Binary tree after inserting node 16:\n" << endl;
|
||||
printTree(bst->getRoot());
|
||||
|
||||
/* Remove node */
|
||||
/* Remove a node */
|
||||
bst->remove(1);
|
||||
cout << endl << "After removing node 1, binary tree is\n" << endl;
|
||||
cout << endl << "Binary tree after removing node 1:\n" << endl;
|
||||
printTree(bst->getRoot());
|
||||
bst->remove(2);
|
||||
cout << endl << "After removing node 2, binary tree is\n" << endl;
|
||||
cout << endl << "Binary tree after removing node 2:\n" << endl;
|
||||
printTree(bst->getRoot());
|
||||
bst->remove(4);
|
||||
cout << endl << "After removing node 4, binary tree is\n" << endl;
|
||||
cout << endl << "Binary tree after removing node 4:\n" << endl;
|
||||
printTree(bst->getRoot());
|
||||
|
||||
// Free memory
|
||||
|
||||
@@ -6,34 +6,34 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Initialize binary tree */
|
||||
// Initialize nodes
|
||||
/* Initialize the binary tree */
|
||||
// Initialize the 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);
|
||||
// Build references (pointers) between nodes
|
||||
// Set up references (pointers) between the nodes
|
||||
n1->left = n2;
|
||||
n1->right = n3;
|
||||
n2->left = n4;
|
||||
n2->right = n5;
|
||||
cout << endl << "Initialize binary tree\n" << endl;
|
||||
cout << endl << "Initialize the binary tree\n" << endl;
|
||||
printTree(n1);
|
||||
|
||||
/* Insert node P between n1 -> n2 */
|
||||
/* Insert and remove nodes */
|
||||
TreeNode *P = new TreeNode(0);
|
||||
// Delete node
|
||||
// Insert node P between n1 and n2 in n1 -> n2
|
||||
n1->left = P;
|
||||
P->left = n2;
|
||||
cout << endl << "After inserting node P\n" << endl;
|
||||
cout << endl << "After inserting node P:\n" << endl;
|
||||
printTree(n1);
|
||||
// Remove node P
|
||||
n1->left = n2;
|
||||
delete P; // Free memory
|
||||
cout << endl << "After removing node P\n" << endl;
|
||||
cout << endl << "After removing node P:\n" << endl;
|
||||
printTree(n1);
|
||||
|
||||
// Free memory
|
||||
|
||||
@@ -8,34 +8,34 @@
|
||||
|
||||
/* Level-order traversal */
|
||||
vector<int> levelOrder(TreeNode *root) {
|
||||
// Initialize queue, add root node
|
||||
// Initialize a queue and enqueue the root
|
||||
queue<TreeNode *> queue;
|
||||
queue.push(root);
|
||||
// Initialize a list to save the traversal sequence
|
||||
// Initialize a list to store the traversal sequence
|
||||
vector<int> vec;
|
||||
while (!queue.empty()) {
|
||||
TreeNode *node = queue.front();
|
||||
queue.pop(); // Dequeue
|
||||
vec.push_back(node->val); // Save node value
|
||||
queue.pop(); // Dequeue from the queue
|
||||
vec.push_back(node->val); // Store the node value
|
||||
if (node->left != nullptr)
|
||||
queue.push(node->left); // Left child node enqueue
|
||||
queue.push(node->left); // Enqueue the left child
|
||||
if (node->right != nullptr)
|
||||
queue.push(node->right); // Right child node enqueue
|
||||
queue.push(node->right); // Enqueue the right child
|
||||
}
|
||||
return vec;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Initialize binary tree */
|
||||
// Here we use a function to generate a binary tree directly from an array
|
||||
/* Initialize the binary tree */
|
||||
// Use a helper function that builds 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;
|
||||
cout << endl << "Initialize the binary tree\n" << endl;
|
||||
printTree(root);
|
||||
|
||||
/* Level-order traversal */
|
||||
vector<int> vec = levelOrder(root);
|
||||
cout << endl << "Level-order traversal node print sequence = ";
|
||||
cout << endl << "Node sequence from level-order traversal = ";
|
||||
printVector(vec);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -6,14 +6,14 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
// Initialize list for storing traversal sequence
|
||||
// Initialize a list to store the traversal sequence
|
||||
vector<int> vec;
|
||||
|
||||
/* Preorder traversal */
|
||||
void preOrder(TreeNode *root) {
|
||||
if (root == nullptr)
|
||||
return;
|
||||
// Visit priority: root node -> left subtree -> right subtree
|
||||
// Visit order: root -> left subtree -> right subtree
|
||||
vec.push_back(root->val);
|
||||
preOrder(root->left);
|
||||
preOrder(root->right);
|
||||
@@ -23,7 +23,7 @@ void preOrder(TreeNode *root) {
|
||||
void inOrder(TreeNode *root) {
|
||||
if (root == nullptr)
|
||||
return;
|
||||
// Visit priority: left subtree -> root node -> right subtree
|
||||
// Visit order: left subtree -> root -> right subtree
|
||||
inOrder(root->left);
|
||||
vec.push_back(root->val);
|
||||
inOrder(root->right);
|
||||
@@ -33,36 +33,36 @@ void inOrder(TreeNode *root) {
|
||||
void postOrder(TreeNode *root) {
|
||||
if (root == nullptr)
|
||||
return;
|
||||
// Visit priority: left subtree -> right subtree -> root node
|
||||
// Visit order: left subtree -> right subtree -> root
|
||||
postOrder(root->left);
|
||||
postOrder(root->right);
|
||||
vec.push_back(root->val);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Initialize binary tree */
|
||||
// Here we use a function to generate a binary tree directly from an array
|
||||
/* Initialize the binary tree */
|
||||
// Use a helper function that builds 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;
|
||||
cout << endl << "Initialize the binary tree\n" << endl;
|
||||
printTree(root);
|
||||
|
||||
/* Preorder traversal */
|
||||
vec.clear();
|
||||
preOrder(root);
|
||||
cout << endl << "Pre-order traversal node print sequence = ";
|
||||
cout << endl << "Node sequence from preorder traversal = ";
|
||||
printVector(vec);
|
||||
|
||||
/* Inorder traversal */
|
||||
vec.clear();
|
||||
inOrder(root);
|
||||
cout << endl << "In-order traversal node print sequence = ";
|
||||
cout << endl << "Node sequence from inorder traversal = ";
|
||||
printVector(vec);
|
||||
|
||||
/* Postorder traversal */
|
||||
vec.clear();
|
||||
postOrder(root);
|
||||
cout << endl << "Post-order traversal node print sequence = ";
|
||||
cout << endl << "Node sequence from postorder traversal = ";
|
||||
printVector(vec);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -30,7 +30,7 @@ ListNode *vecToLinkedList(vector<int> list) {
|
||||
return dum->next;
|
||||
}
|
||||
|
||||
/* Free memory allocated to linked list */
|
||||
/* Free the memory allocated to the linked list */
|
||||
void freeMemoryLinkedList(ListNode *cur) {
|
||||
// Free memory
|
||||
ListNode *pre;
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
/* Find an element in a vector */
|
||||
/* Find the last matching element's index in a vector */
|
||||
template <typename T> int vecFind(const vector<T> &vec, T ele) {
|
||||
int j = INT_MAX;
|
||||
for (int i = 0; i < vec.size(); i++) {
|
||||
@@ -24,7 +24,7 @@ template <typename T> int vecFind(const vector<T> &vec, T ele) {
|
||||
return j;
|
||||
}
|
||||
|
||||
/* Concatenate a vector with a delim */
|
||||
/* Join vector elements with a delimiter */
|
||||
template <typename T> string strJoin(const string &delim, const T &vec) {
|
||||
ostringstream s;
|
||||
for (const auto &i : vec) {
|
||||
@@ -36,7 +36,7 @@ template <typename T> string strJoin(const string &delim, const T &vec) {
|
||||
return s.str();
|
||||
}
|
||||
|
||||
/* Repeat a string for n times */
|
||||
/* Repeat a string n times */
|
||||
string strRepeat(string str, int n) {
|
||||
ostringstream os;
|
||||
for (int i = 0; i < n; i++)
|
||||
@@ -44,7 +44,7 @@ string strRepeat(string str, int n) {
|
||||
return os.str();
|
||||
}
|
||||
|
||||
/* Print array */
|
||||
/* Print an array */
|
||||
template <typename T> void printArray(T *arr, int n) {
|
||||
cout << "[";
|
||||
for (int i = 0; i < n - 1; i++) {
|
||||
@@ -56,17 +56,17 @@ template <typename T> void printArray(T *arr, int n) {
|
||||
cout << "]" << endl;
|
||||
}
|
||||
|
||||
/* Get the Vector String object */
|
||||
/* Get a string representation of a vector */
|
||||
template <typename T> string getVectorString(vector<T> &list) {
|
||||
return "[" + strJoin(", ", list) + "]";
|
||||
}
|
||||
|
||||
/* Print list */
|
||||
/* Print the list */
|
||||
template <typename T> void printVector(vector<T> list) {
|
||||
cout << getVectorString(list) << '\n';
|
||||
}
|
||||
|
||||
/* Print matrix */
|
||||
/* Print a matrix */
|
||||
template <typename T> void printVectorMatrix(vector<vector<T>> &matrix) {
|
||||
cout << "[" << '\n';
|
||||
for (vector<T> &list : matrix)
|
||||
@@ -74,7 +74,7 @@ template <typename T> void printVectorMatrix(vector<vector<T>> &matrix) {
|
||||
cout << "]" << '\n';
|
||||
}
|
||||
|
||||
/* Print linked list */
|
||||
/* Print a linked list */
|
||||
void printLinkedList(ListNode *head) {
|
||||
vector<int> list;
|
||||
while (head != nullptr) {
|
||||
@@ -104,7 +104,7 @@ void showTrunks(Trunk *p) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 打印二叉树
|
||||
* Print a binary tree
|
||||
* This tree printer is borrowed from TECHIE DELIGHT
|
||||
* https://www.techiedelight.com/c-program-print-binary-tree/
|
||||
*/
|
||||
@@ -139,12 +139,12 @@ void printTree(TreeNode *root, Trunk *prev, bool isRight) {
|
||||
printTree(root->left, &trunk, false);
|
||||
}
|
||||
|
||||
/* Print binary tree */
|
||||
/* Print a binary tree */
|
||||
void printTree(TreeNode *root) {
|
||||
printTree(root, nullptr, false);
|
||||
}
|
||||
|
||||
/* Print stack */
|
||||
/* Print the stack */
|
||||
template <typename T> void printStack(stack<T> stk) {
|
||||
// Reverse the input stack
|
||||
stack<T> tmp;
|
||||
@@ -166,7 +166,7 @@ template <typename T> void printStack(stack<T> stk) {
|
||||
cout << "[" + s.str() + "]" << '\n';
|
||||
}
|
||||
|
||||
/* Print queue */
|
||||
/* Print the queue */
|
||||
template <typename T> void printQueue(queue<T> queue) {
|
||||
// Generate the string to print
|
||||
ostringstream s;
|
||||
@@ -182,7 +182,7 @@ template <typename T> void printQueue(queue<T> queue) {
|
||||
cout << "[" + s.str() + "]" << '\n';
|
||||
}
|
||||
|
||||
/* Print deque */
|
||||
/* Print the deque */
|
||||
template <typename T> void printDeque(deque<T> deque) {
|
||||
// Generate the string to print
|
||||
ostringstream s;
|
||||
@@ -198,8 +198,8 @@ template <typename T> void printDeque(deque<T> deque) {
|
||||
cout << "[" + s.str() + "]" << '\n';
|
||||
}
|
||||
|
||||
/* Print hash table */
|
||||
// Define template parameters TKey and TValue to specify key-value pair types
|
||||
/* Print the hash table */
|
||||
// Define template parameters TKey and TValue for the key and value 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 the heap (priority queue) */
|
||||
template <typename T, typename S, typename C> void printHeap(priority_queue<T, S, C> &heap) {
|
||||
vector<T> vec = Container(heap);
|
||||
cout << "Heap array representation:";
|
||||
cout << "Array representation of the heap:";
|
||||
printVector(vec);
|
||||
cout << "Heap tree representation:" << endl;
|
||||
cout << "Tree representation of the heap:" << endl;
|
||||
TreeNode *root = vectorToTree(vec);
|
||||
printTree(root);
|
||||
freeMemoryTree(root);
|
||||
|
||||
@@ -23,11 +23,11 @@ struct TreeNode {
|
||||
}
|
||||
};
|
||||
|
||||
// For the serialization encoding rules, please refer to:
|
||||
// https://www.hello-algo.com/chapter_tree/array_representation_of_tree/
|
||||
// Array representation of binary tree:
|
||||
// For the serialization rules, see:
|
||||
// https://www.hello-algo.com/en/chapter_tree/array_representation_of_tree/
|
||||
// Array representation of the binary tree:
|
||||
// [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15]
|
||||
// Linked list representation of binary tree:
|
||||
// Linked representation of the binary tree:
|
||||
// /——— 15
|
||||
// /——— 7
|
||||
// /——— 3
|
||||
@@ -74,7 +74,7 @@ vector<int> treeToVecor(TreeNode *root) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Free binary tree memory */
|
||||
/* Free the binary tree memory */
|
||||
void freeMemoryTree(TreeNode *root) {
|
||||
if (root == nullptr)
|
||||
return;
|
||||
|
||||
@@ -17,7 +17,7 @@ struct Vertex {
|
||||
}
|
||||
};
|
||||
|
||||
/* Input value list vals, return vertex list vets */
|
||||
/* Given the list of values vals, return the list of vertices 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 vertex list vets, return value list vals */
|
||||
/* Given the list of vertices vets, return the list of values vals */
|
||||
vector<int> vetsToVals(vector<Vertex *> vets) {
|
||||
vector<int> vals;
|
||||
for (Vertex *vet : vets) {
|
||||
|
||||
Reference in New Issue
Block a user