mirror of
https://github.com/krahets/hello-algo.git
synced 2026-09-02 05:07:13 +00:00
Translate all code to English (#1836)
* Review the EN heading format. * Fix pythontutor headings. * Fix pythontutor headings. * bug fixes * Fix headings in **/summary.md * Revisit the CN-to-EN translation for Python code using Claude-4.5 * Revisit the CN-to-EN translation for Java code using Claude-4.5 * Revisit the CN-to-EN translation for Cpp code using Claude-4.5. * Fix the dictionary. * Fix cpp code translation for the multipart strings. * Translate Go code to English. * Update workflows to test EN code. * Add EN translation for C. * Add EN translation for CSharp. * Add EN translation for Swift. * Trigger the CI check. * Revert. * Update en/hash_map.md * Add the EN version of Dart code. * Add the EN version of Kotlin code. * Add missing code files. * Add the EN version of JavaScript code. * Add the EN version of TypeScript code. * Fix the workflows. * Add the EN version of Ruby code. * Add the EN version of Rust code. * Update the CI check for the English version code. * Update Python CI check. * Fix cmakelists for en/C code. * Fix Ruby comments
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
import 'dart:io';
|
||||
|
||||
void main() {
|
||||
Directory foldPath = Directory('codes/dart/');
|
||||
List<FileSystemEntity> files = foldPath.listSync();
|
||||
int totalCount = 0;
|
||||
int errorCount = 0;
|
||||
for (var file in files) {
|
||||
if (file.path.endsWith('build.dart')) continue;
|
||||
if (file is File && file.path.endsWith('.dart')) {
|
||||
totalCount++;
|
||||
try {
|
||||
Process.runSync('dart', [file.path]);
|
||||
} catch (e) {
|
||||
errorCount++;
|
||||
print('Error: $e');
|
||||
print('File: ${file.path}');
|
||||
}
|
||||
} else if (file is Directory) {
|
||||
List<FileSystemEntity> subFiles = file.listSync();
|
||||
for (var subFile in subFiles) {
|
||||
if (subFile is File && subFile.path.endsWith('.dart')) {
|
||||
totalCount++;
|
||||
try {
|
||||
Process.runSync('dart', [subFile.path]);
|
||||
} catch (e) {
|
||||
errorCount++;
|
||||
print('Error: $e');
|
||||
print('File: ${file.path}');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
print('===== Build Complete =====');
|
||||
print('Total: $totalCount');
|
||||
print('Error: $errorCount');
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* File: array.dart
|
||||
* Created Time: 2023-01-20
|
||||
* Author: Jefferson (JeffersonHuang77@gmail.com)
|
||||
*/
|
||||
|
||||
// ignore_for_file: unused_local_variable
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
/* Random access to element */
|
||||
int randomAccess(List<int> nums) {
|
||||
// Randomly select a number in the interval [0, nums.length)
|
||||
int randomIndex = Random().nextInt(nums.length);
|
||||
// Retrieve and return the random element
|
||||
int randomNum = nums[randomIndex];
|
||||
return randomNum;
|
||||
}
|
||||
|
||||
/* Extend array length */
|
||||
List<int> extend(List<int> nums, int enlarge) {
|
||||
// Initialize an array with extended length
|
||||
List<int> res = List.filled(nums.length + enlarge, 0);
|
||||
// Copy all elements from the original array to the new array
|
||||
for (var i = 0; i < nums.length; i++) {
|
||||
res[i] = nums[i];
|
||||
}
|
||||
// Return the extended new array
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Insert element _num at array index index */
|
||||
void insert(List<int> nums, int _num, int index) {
|
||||
// Move all elements at and after index index backward by one position
|
||||
for (var i = nums.length - 1; i > index; i--) {
|
||||
nums[i] = nums[i - 1];
|
||||
}
|
||||
// Assign _num to element at index
|
||||
nums[index] = _num;
|
||||
}
|
||||
|
||||
/* Remove the element at index index */
|
||||
void remove(List<int> nums, int index) {
|
||||
// Move all elements after index index forward by one position
|
||||
for (var i = index; i < nums.length - 1; i++) {
|
||||
nums[i] = nums[i + 1];
|
||||
}
|
||||
}
|
||||
|
||||
/* Traverse array elements */
|
||||
void traverse(List<int> nums) {
|
||||
int count = 0;
|
||||
// Traverse array by index
|
||||
for (var i = 0; i < nums.length; i++) {
|
||||
count += nums[i];
|
||||
}
|
||||
// Direct traversal of array elements
|
||||
for (int _num in nums) {
|
||||
count += _num;
|
||||
}
|
||||
// Traverse array using forEach method
|
||||
nums.forEach((_num) {
|
||||
count += _num;
|
||||
});
|
||||
}
|
||||
|
||||
/* Find the specified element in the array */
|
||||
int find(List<int> nums, int target) {
|
||||
for (var i = 0; i < nums.length; i++) {
|
||||
if (nums[i] == target) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
/* Initialize array */
|
||||
var arr = List.filled(5, 0);
|
||||
print('Array arr = $arr');
|
||||
List<int> nums = [1, 3, 2, 5, 4];
|
||||
print('Array nums = $nums');
|
||||
|
||||
/* Insert element */
|
||||
int randomNum = randomAccess(nums);
|
||||
print('Get random element $randomNum from nums');
|
||||
|
||||
/* Traverse array */
|
||||
nums = extend(nums, 3);
|
||||
print('Extend array length to 8, get nums = $nums');
|
||||
|
||||
/* Insert element */
|
||||
insert(nums, 6, 3);
|
||||
print("Insert number 6 at index 3, get nums = $nums");
|
||||
|
||||
/* Remove element */
|
||||
remove(nums, 2);
|
||||
print("Delete element at index 2, get nums = $nums");
|
||||
|
||||
/* Traverse array */
|
||||
traverse(nums);
|
||||
|
||||
/* Find element */
|
||||
int index = find(nums, 3);
|
||||
print("Find element 3 in nums, index = $index");
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* File: linked_list.dart
|
||||
* Created Time: 2023-01-23
|
||||
* Author: Jefferson (JeffersonHuang77@gmail.com)
|
||||
*/
|
||||
|
||||
import '../utils/list_node.dart';
|
||||
import '../utils/print_util.dart';
|
||||
|
||||
/* Insert node P after node n0 in the linked list */
|
||||
void insert(ListNode n0, ListNode P) {
|
||||
ListNode? n1 = n0.next;
|
||||
P.next = n1;
|
||||
n0.next = P;
|
||||
}
|
||||
|
||||
/* Remove the first node after node n0 in the linked list */
|
||||
void remove(ListNode n0) {
|
||||
if (n0.next == null) return;
|
||||
// n0 -> P -> n1
|
||||
ListNode P = n0.next!;
|
||||
ListNode? n1 = P.next;
|
||||
n0.next = n1;
|
||||
}
|
||||
|
||||
/* Access the node at index index in the linked list */
|
||||
ListNode? access(ListNode? head, int index) {
|
||||
for (var i = 0; i < index; i++) {
|
||||
if (head == null) return null;
|
||||
head = head.next;
|
||||
}
|
||||
return head;
|
||||
}
|
||||
|
||||
/* Find the first node with value target in the linked list */
|
||||
int find(ListNode? head, int target) {
|
||||
int index = 0;
|
||||
while (head != null) {
|
||||
if (head.val == target) {
|
||||
return index;
|
||||
}
|
||||
head = head.next;
|
||||
index++;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
// Initialize linked list
|
||||
// Initialize each node
|
||||
ListNode n0 = ListNode(1);
|
||||
ListNode n1 = ListNode(3);
|
||||
ListNode n2 = ListNode(2);
|
||||
ListNode n3 = ListNode(5);
|
||||
ListNode n4 = ListNode(4);
|
||||
// Build references between nodes
|
||||
n0.next = n1;
|
||||
n1.next = n2;
|
||||
n2.next = n3;
|
||||
n3.next = n4;
|
||||
|
||||
print('Initialized linked list is');
|
||||
printLinkedList(n0);
|
||||
|
||||
/* Insert node */
|
||||
insert(n0, ListNode(0));
|
||||
print('Linked list after inserting node is');
|
||||
printLinkedList(n0);
|
||||
|
||||
/* Remove node */
|
||||
remove(n0);
|
||||
print('Linked list after removing node is');
|
||||
printLinkedList(n0);
|
||||
|
||||
/* Access node */
|
||||
ListNode? node = access(n0, 3);
|
||||
print('Value of node at index 3 in linked list = ${node!.val}');
|
||||
|
||||
/* Search node */
|
||||
int index = find(n0, 2);
|
||||
print('Index of node with value 2 in linked list = $index');
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* File: list.dart
|
||||
* Created Time: 2023-01-24
|
||||
* Author: Jefferson (JeffersonHuang77@gmail.com)
|
||||
*/
|
||||
|
||||
// ignore_for_file: unused_local_variable
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
/* Initialize list */
|
||||
List<int> nums = [1, 3, 2, 5, 4];
|
||||
print('List nums = $nums');
|
||||
|
||||
/* Update element */
|
||||
int _num = nums[1];
|
||||
print('Access element at index 1, get _num = $_num');
|
||||
|
||||
/* Add elements at the end */
|
||||
nums[1] = 0;
|
||||
print('Update element at index 1 to 0, get nums = $nums');
|
||||
|
||||
/* Remove element */
|
||||
nums.clear();
|
||||
print('After clearing list, nums = $nums');
|
||||
|
||||
/* Direct traversal of list elements */
|
||||
nums.add(1);
|
||||
nums.add(3);
|
||||
nums.add(2);
|
||||
nums.add(5);
|
||||
nums.add(4);
|
||||
print('After adding elements, nums = $nums');
|
||||
|
||||
/* Sort list */
|
||||
nums.insert(3, 6);
|
||||
print('Insert number 6 at index 3, get nums = $nums');
|
||||
|
||||
/* Remove element */
|
||||
nums.removeAt(3);
|
||||
print('Delete element at index 3, get nums = $nums');
|
||||
|
||||
/* Traverse list by index */
|
||||
int count = 0;
|
||||
for (var i = 0; i < nums.length; i++) {
|
||||
count += nums[i];
|
||||
}
|
||||
/* Directly traverse list elements */
|
||||
count = 0;
|
||||
for (var x in nums) {
|
||||
count += x;
|
||||
}
|
||||
|
||||
/* Concatenate two lists */
|
||||
List<int> nums1 = [6, 8, 7, 10, 9];
|
||||
nums.addAll(nums1);
|
||||
print('After concatenating list nums1 to nums, get nums = $nums');
|
||||
|
||||
/* Sort list */
|
||||
nums.sort();
|
||||
print('After sorting list, nums = $nums');
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* File: my_list.dart
|
||||
* Created Time: 2023-02-05
|
||||
* Author: Jefferson (JeffersonHuang77@gmail.com)
|
||||
*/
|
||||
|
||||
/* List class */
|
||||
class MyList {
|
||||
late List<int> _arr; // Array (stores list elements)
|
||||
int _capacity = 10; // List capacity
|
||||
int _size = 0; // List length (current number of elements)
|
||||
int _extendRatio = 2; // Multiple by which the list capacity is extended each time
|
||||
|
||||
/* Constructor */
|
||||
MyList() {
|
||||
_arr = List.filled(_capacity, 0);
|
||||
}
|
||||
|
||||
/* Get list length (current number of elements) */
|
||||
int size() => _size;
|
||||
|
||||
/* Get list capacity */
|
||||
int capacity() => _capacity;
|
||||
|
||||
/* Update element */
|
||||
int get(int index) {
|
||||
if (index >= _size) throw RangeError('Index out of bounds');
|
||||
return _arr[index];
|
||||
}
|
||||
|
||||
/* Add elements at the end */
|
||||
void set(int index, int _num) {
|
||||
if (index >= _size) throw RangeError('Index out of bounds');
|
||||
_arr[index] = _num;
|
||||
}
|
||||
|
||||
/* Direct traversal of list elements */
|
||||
void add(int _num) {
|
||||
// When the number of elements exceeds capacity, trigger the extension mechanism
|
||||
if (_size == _capacity) extendCapacity();
|
||||
_arr[_size] = _num;
|
||||
// Update the number of elements
|
||||
_size++;
|
||||
}
|
||||
|
||||
/* Sort list */
|
||||
void insert(int index, int _num) {
|
||||
if (index >= _size) throw RangeError('Index out of bounds');
|
||||
// When the number of elements exceeds capacity, trigger the extension mechanism
|
||||
if (_size == _capacity) extendCapacity();
|
||||
// Move all elements after index index forward by one position
|
||||
for (var j = _size - 1; j >= index; j--) {
|
||||
_arr[j + 1] = _arr[j];
|
||||
}
|
||||
_arr[index] = _num;
|
||||
// Update the number of elements
|
||||
_size++;
|
||||
}
|
||||
|
||||
/* Remove element */
|
||||
int remove(int index) {
|
||||
if (index >= _size) throw RangeError('Index out of bounds');
|
||||
int _num = _arr[index];
|
||||
// Move all elements after index forward by one position
|
||||
for (var j = index; j < _size - 1; j++) {
|
||||
_arr[j] = _arr[j + 1];
|
||||
}
|
||||
// Update the number of elements
|
||||
_size--;
|
||||
// Return the removed element
|
||||
return _num;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void extendCapacity() {
|
||||
// Create new array with length _extendRatio times original array
|
||||
final _newNums = List.filled(_capacity * _extendRatio, 0);
|
||||
// Copy original array to new array
|
||||
List.copyRange(_newNums, 0, _arr);
|
||||
// Update _arr reference
|
||||
_arr = _newNums;
|
||||
// Add elements at the end
|
||||
_capacity = _arr.length;
|
||||
}
|
||||
|
||||
/* Convert list to array */
|
||||
List<int> toArray() {
|
||||
List<int> arr = [];
|
||||
for (var i = 0; i < _size; i++) {
|
||||
arr.add(get(i));
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
/* Initialize list */
|
||||
MyList nums = MyList();
|
||||
/* Direct traversal of list elements */
|
||||
nums.add(1);
|
||||
nums.add(3);
|
||||
nums.add(2);
|
||||
nums.add(5);
|
||||
nums.add(4);
|
||||
print(
|
||||
'List nums = ${nums.toArray()}, capacity = ${nums.capacity()}, length = ${nums.size()}');
|
||||
|
||||
/* Sort list */
|
||||
nums.insert(3, 6);
|
||||
print('Insert number 6 at index 3, get nums = ${nums.toArray()}');
|
||||
|
||||
/* Remove element */
|
||||
nums.remove(3);
|
||||
print('Delete element at index 3, get nums = ${nums.toArray()}');
|
||||
|
||||
/* Update element */
|
||||
int _num = nums.get(1);
|
||||
print('Access element at index 1, get _num = $_num');
|
||||
|
||||
/* Add elements at the end */
|
||||
nums.set(1, 0);
|
||||
print('Update element at index 1 to 0, get nums = ${nums.toArray()}');
|
||||
|
||||
/* Test capacity expansion mechanism */
|
||||
for (var i = 0; i < 10; i++) {
|
||||
// At i = 5, the list length will exceed the list capacity, triggering the expansion mechanism
|
||||
nums.add(i);
|
||||
}
|
||||
print(
|
||||
'After expansion, list nums = ${nums.toArray()}, capacity = ${nums.capacity()}, length = ${nums.size()}');
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* File: n_queens.dart
|
||||
* Created Time: 2023-08-10
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: N queens */
|
||||
void backtrack(
|
||||
int row,
|
||||
int n,
|
||||
List<List<String>> state,
|
||||
List<List<List<String>>> res,
|
||||
List<bool> cols,
|
||||
List<bool> diags1,
|
||||
List<bool> diags2,
|
||||
) {
|
||||
// When all rows are placed, record the solution
|
||||
if (row == n) {
|
||||
List<List<String>> copyState = [];
|
||||
for (List<String> sRow in state) {
|
||||
copyState.add(List.from(sRow));
|
||||
}
|
||||
res.add(copyState);
|
||||
return;
|
||||
}
|
||||
// Traverse all columns
|
||||
for (int col = 0; col < n; col++) {
|
||||
// Calculate the main diagonal and anti-diagonal corresponding to this cell
|
||||
int diag1 = row - col + n - 1;
|
||||
int diag2 = row + col;
|
||||
// Pruning: do not allow queens to exist in the column, main diagonal, and anti-diagonal of this cell
|
||||
if (!cols[col] && !diags1[diag1] && !diags2[diag2]) {
|
||||
// Attempt: place the queen in this cell
|
||||
state[row][col] = "Q";
|
||||
cols[col] = true;
|
||||
diags1[diag1] = true;
|
||||
diags2[diag2] = true;
|
||||
// Place the next row
|
||||
backtrack(row + 1, n, state, res, cols, diags1, diags2);
|
||||
// Backtrack: restore this cell to an empty cell
|
||||
state[row][col] = "#";
|
||||
cols[col] = false;
|
||||
diags1[diag1] = false;
|
||||
diags2[diag2] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Solve N queens */
|
||||
List<List<List<String>>> nQueens(int n) {
|
||||
// Initialize an n*n chessboard, where 'Q' represents a queen and '#' represents an empty cell
|
||||
List<List<String>> state = List.generate(n, (index) => List.filled(n, "#"));
|
||||
List<bool> cols = List.filled(n, false); // Record whether there is a queen in the column
|
||||
List<bool> diags1 = List.filled(2 * n - 1, false); // Record whether there is a queen on the main diagonal
|
||||
List<bool> diags2 = List.filled(2 * n - 1, false); // Record whether there is a queen on the anti-diagonal
|
||||
List<List<List<String>>> res = [];
|
||||
|
||||
backtrack(0, n, state, res, cols, diags1, diags2);
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
int n = 4;
|
||||
List<List<List<String>>> res = nQueens(n);
|
||||
print("Input board size is $n");
|
||||
print("Total queen placement solutions: ${res.length}");
|
||||
for (List<List<String>> state in res) {
|
||||
print("--------------------");
|
||||
for (List<String> row in state) {
|
||||
print(row);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* File: permutations_i.dart
|
||||
* Created Time: 2023-08-10
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Permutations I */
|
||||
void backtrack(
|
||||
List<int> state,
|
||||
List<int> choices,
|
||||
List<bool> selected,
|
||||
List<List<int>> res,
|
||||
) {
|
||||
// When the state length equals the number of elements, record the solution
|
||||
if (state.length == choices.length) {
|
||||
res.add(List.from(state));
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
for (int i = 0; i < choices.length; i++) {
|
||||
int choice = choices[i];
|
||||
// Pruning: do not allow repeated selection of elements
|
||||
if (!selected[i]) {
|
||||
// Attempt: make choice, update state
|
||||
selected[i] = true;
|
||||
state.add(choice);
|
||||
// Proceed to the next round of selection
|
||||
backtrack(state, choices, selected, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
selected[i] = false;
|
||||
state.removeLast();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Permutations I */
|
||||
List<List<int>> permutationsI(List<int> nums) {
|
||||
List<List<int>> res = [];
|
||||
backtrack([], nums, List.filled(nums.length, false), res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
List<int> nums = [1, 2, 3];
|
||||
|
||||
List<List<int>> res = permutationsI(nums);
|
||||
|
||||
print("Input array nums = $nums");
|
||||
print("All permutations res = $res");
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* File: permutations_ii.dart
|
||||
* Created Time: 2023-08-10
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Permutations II */
|
||||
void backtrack(
|
||||
List<int> state,
|
||||
List<int> choices,
|
||||
List<bool> selected,
|
||||
List<List<int>> res,
|
||||
) {
|
||||
// When the state length equals the number of elements, record the solution
|
||||
if (state.length == choices.length) {
|
||||
res.add(List.from(state));
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
Set<int> duplicated = {};
|
||||
for (int i = 0; i < choices.length; i++) {
|
||||
int choice = choices[i];
|
||||
// Pruning: do not allow repeated selection of elements and do not allow repeated selection of equal elements
|
||||
if (!selected[i] && !duplicated.contains(choice)) {
|
||||
// Attempt: make choice, update state
|
||||
duplicated.add(choice); // Record the selected element value
|
||||
selected[i] = true;
|
||||
state.add(choice);
|
||||
// Proceed to the next round of selection
|
||||
backtrack(state, choices, selected, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
selected[i] = false;
|
||||
state.removeLast();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Permutations II */
|
||||
List<List<int>> permutationsII(List<int> nums) {
|
||||
List<List<int>> res = [];
|
||||
backtrack([], nums, List.filled(nums.length, false), res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
List<int> nums = [1, 2, 2];
|
||||
|
||||
List<List<int>> res = permutationsII(nums);
|
||||
|
||||
print("Input array nums = $nums");
|
||||
print("All permutations res = $res");
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* File: preorder_traversal_i_compact.dart
|
||||
* Created Time: 2023-08-10
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import '../utils/print_util.dart';
|
||||
import '../utils/tree_node.dart';
|
||||
|
||||
/* Preorder traversal: Example 1 */
|
||||
void preOrder(TreeNode? root, List<TreeNode> res) {
|
||||
if (root == null) {
|
||||
return;
|
||||
}
|
||||
if (root.val == 7) {
|
||||
// Record solution
|
||||
res.add(root);
|
||||
}
|
||||
preOrder(root.left, res);
|
||||
preOrder(root.right, res);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
TreeNode? root = listToTree([1, 7, 3, 4, 5, 6, 7]);
|
||||
print("\nInitialize binary tree");
|
||||
printTree(root);
|
||||
|
||||
// Preorder traversal
|
||||
List<TreeNode> res = [];
|
||||
preOrder(root, res);
|
||||
|
||||
print("\nOutput all nodes with value 7");
|
||||
print(List.generate(res.length, (i) => res[i].val));
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* File: preorder_traversal_ii_compact.dart
|
||||
* Created Time: 2023-08-10
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import '../utils/print_util.dart';
|
||||
import '../utils/tree_node.dart';
|
||||
|
||||
/* Preorder traversal: Example 2 */
|
||||
void preOrder(
|
||||
TreeNode? root,
|
||||
List<TreeNode> path,
|
||||
List<List<TreeNode>> res,
|
||||
) {
|
||||
if (root == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Attempt
|
||||
path.add(root);
|
||||
if (root.val == 7) {
|
||||
// Record solution
|
||||
res.add(List.from(path));
|
||||
}
|
||||
preOrder(root.left, path, res);
|
||||
preOrder(root.right, path, res);
|
||||
// Backtrack
|
||||
path.removeLast();
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
TreeNode? root = listToTree([1, 7, 3, 4, 5, 6, 7]);
|
||||
print("\nInitialize binary tree");
|
||||
printTree(root);
|
||||
|
||||
// Preorder traversal
|
||||
List<TreeNode> path = [];
|
||||
List<List<TreeNode>> res = [];
|
||||
preOrder(root, path, res);
|
||||
|
||||
print("\nOutput all paths from root node to node 7");
|
||||
for (List<TreeNode> vals in res) {
|
||||
print(List.generate(vals.length, (i) => vals[i].val));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* File: preorder_traversal_iii_compact.dart
|
||||
* Created Time: 2023-08-10
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import '../utils/print_util.dart';
|
||||
import '../utils/tree_node.dart';
|
||||
|
||||
/* Preorder traversal: Example 3 */
|
||||
void preOrder(
|
||||
TreeNode? root,
|
||||
List<TreeNode> path,
|
||||
List<List<TreeNode>> res,
|
||||
) {
|
||||
if (root == null || root.val == 3) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Attempt
|
||||
path.add(root);
|
||||
if (root.val == 7) {
|
||||
// Record solution
|
||||
res.add(List.from(path));
|
||||
}
|
||||
preOrder(root.left, path, res);
|
||||
preOrder(root.right, path, res);
|
||||
// Backtrack
|
||||
path.removeLast();
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
TreeNode? root = listToTree([1, 7, 3, 4, 5, 6, 7]);
|
||||
print("\nInitialize binary tree");
|
||||
printTree(root);
|
||||
|
||||
// Preorder traversal
|
||||
List<TreeNode> path = [];
|
||||
List<List<TreeNode>> res = [];
|
||||
preOrder(root, path, res);
|
||||
|
||||
print("\nOutput all paths from root node to node 7");
|
||||
for (List<TreeNode> vals in res) {
|
||||
print(List.generate(vals.length, (i) => vals[i].val));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* File: preorder_traversal_iii_template.dart
|
||||
* Created Time: 2023-08-10
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import '../utils/print_util.dart';
|
||||
import '../utils/tree_node.dart';
|
||||
|
||||
/* Check if the current state is a solution */
|
||||
bool isSolution(List<TreeNode> state) {
|
||||
return state.isNotEmpty && state.last.val == 7;
|
||||
}
|
||||
|
||||
/* Record solution */
|
||||
void recordSolution(List<TreeNode> state, List<List<TreeNode>> res) {
|
||||
res.add(List.from(state));
|
||||
}
|
||||
|
||||
/* Check if the choice is valid under the current state */
|
||||
bool isValid(List<TreeNode> state, TreeNode? choice) {
|
||||
return choice != null && choice.val != 3;
|
||||
}
|
||||
|
||||
/* Update state */
|
||||
void makeChoice(List<TreeNode> state, TreeNode? choice) {
|
||||
state.add(choice!);
|
||||
}
|
||||
|
||||
/* Restore state */
|
||||
void undoChoice(List<TreeNode> state, TreeNode? choice) {
|
||||
state.removeLast();
|
||||
}
|
||||
|
||||
/* Backtracking algorithm: Example 3 */
|
||||
void backtrack(
|
||||
List<TreeNode> state,
|
||||
List<TreeNode?> choices,
|
||||
List<List<TreeNode>> res,
|
||||
) {
|
||||
// Check if it is a solution
|
||||
if (isSolution(state)) {
|
||||
// Record solution
|
||||
recordSolution(state, res);
|
||||
}
|
||||
// Traverse all choices
|
||||
for (TreeNode? choice in choices) {
|
||||
// Pruning: check if the choice is valid
|
||||
if (isValid(state, choice)) {
|
||||
// Attempt: make choice, update state
|
||||
makeChoice(state, choice);
|
||||
// Proceed to the next round of selection
|
||||
backtrack(state, [choice!.left, choice.right], res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
undoChoice(state, choice);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
TreeNode? root = listToTree([1, 7, 3, 4, 5, 6, 7]);
|
||||
print("\nInitialize binary tree");
|
||||
printTree(root);
|
||||
|
||||
// Backtracking algorithm
|
||||
List<List<TreeNode>> res = [];
|
||||
backtrack([], [root!], res);
|
||||
print("\nOutput all paths from root node to node 7, requiring paths do not include nodes with value 3");
|
||||
for (List<TreeNode> path in res) {
|
||||
print(List.from(path.map((e) => e.val)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* File: subset_sum_i.dart
|
||||
* Created Time: 2023-08-10
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Subset sum I */
|
||||
void backtrack(
|
||||
List<int> state,
|
||||
int target,
|
||||
List<int> choices,
|
||||
int start,
|
||||
List<List<int>> res,
|
||||
) {
|
||||
// When the subset sum equals target, record the solution
|
||||
if (target == 0) {
|
||||
res.add(List.from(state));
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
// Pruning 2: start traversing from start to avoid generating duplicate subsets
|
||||
for (int i = start; i < choices.length; i++) {
|
||||
// Pruning 1: if the subset sum exceeds target, end the loop directly
|
||||
// This is because the array is sorted, and later elements are larger, so the subset sum will definitely exceed target
|
||||
if (target - choices[i] < 0) {
|
||||
break;
|
||||
}
|
||||
// Attempt: make choice, update target, start
|
||||
state.add(choices[i]);
|
||||
// Proceed to the next round of selection
|
||||
backtrack(state, target - choices[i], choices, i, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
state.removeLast();
|
||||
}
|
||||
}
|
||||
|
||||
/* Solve subset sum I */
|
||||
List<List<int>> subsetSumI(List<int> nums, int target) {
|
||||
List<int> state = []; // State (subset)
|
||||
nums.sort(); // Sort nums
|
||||
int start = 0; // Start point for traversal
|
||||
List<List<int>> res = []; // Result list (subset list)
|
||||
backtrack(state, target, nums, start, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
List<int> nums = [3, 4, 5];
|
||||
int target = 9;
|
||||
|
||||
List<List<int>> res = subsetSumI(nums, target);
|
||||
|
||||
print("Input array nums = $nums, target = $target");
|
||||
print("All subsets with sum equal to $target res = $res");
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* File: subset_sum_i_naive.dart
|
||||
* Created Time: 2023-08-10
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Subset sum I */
|
||||
void backtrack(
|
||||
List<int> state,
|
||||
int target,
|
||||
int total,
|
||||
List<int> choices,
|
||||
List<List<int>> res,
|
||||
) {
|
||||
// When the subset sum equals target, record the solution
|
||||
if (total == target) {
|
||||
res.add(List.from(state));
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
for (int i = 0; i < choices.length; i++) {
|
||||
// Pruning: if the subset sum exceeds target, skip this choice
|
||||
if (total + choices[i] > target) {
|
||||
continue;
|
||||
}
|
||||
// Attempt: make choice, update element sum total
|
||||
state.add(choices[i]);
|
||||
// Proceed to the next round of selection
|
||||
backtrack(state, target, total + choices[i], choices, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
state.removeLast();
|
||||
}
|
||||
}
|
||||
|
||||
/* Solve subset sum I (including duplicate subsets) */
|
||||
List<List<int>> subsetSumINaive(List<int> nums, int target) {
|
||||
List<int> state = []; // State (subset)
|
||||
int total = 0; // Sum of elements
|
||||
List<List<int>> res = []; // Result list (subset list)
|
||||
backtrack(state, target, total, nums, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
List<int> nums = [3, 4, 5];
|
||||
int target = 9;
|
||||
|
||||
List<List<int>> res = subsetSumINaive(nums, target);
|
||||
|
||||
print("Input array nums = $nums, target = $target");
|
||||
print("All subsets with sum equal to $target res = $res");
|
||||
print("Please note that this method outputs results containing duplicate sets");
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* File: subset_sum_ii.dart
|
||||
* Created Time: 2023-08-10
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Subset sum II */
|
||||
void backtrack(
|
||||
List<int> state,
|
||||
int target,
|
||||
List<int> choices,
|
||||
int start,
|
||||
List<List<int>> res,
|
||||
) {
|
||||
// When the subset sum equals target, record the solution
|
||||
if (target == 0) {
|
||||
res.add(List.from(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
|
||||
for (int i = start; i < choices.length; i++) {
|
||||
// Pruning 1: if the subset sum exceeds target, end the loop directly
|
||||
// This is because the array is sorted, and later elements are larger, so the subset sum will definitely exceed target
|
||||
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
|
||||
if (i > start && choices[i] == choices[i - 1]) {
|
||||
continue;
|
||||
}
|
||||
// Attempt: make choice, update target, start
|
||||
state.add(choices[i]);
|
||||
// Proceed to the next round of selection
|
||||
backtrack(state, target - choices[i], choices, i + 1, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
state.removeLast();
|
||||
}
|
||||
}
|
||||
|
||||
/* Solve subset sum II */
|
||||
List<List<int>> subsetSumII(List<int> nums, int target) {
|
||||
List<int> state = []; // State (subset)
|
||||
nums.sort(); // Sort nums
|
||||
int start = 0; // Start point for traversal
|
||||
List<List<int>> res = []; // Result list (subset list)
|
||||
backtrack(state, target, nums, start, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
List<int> nums = [4, 4, 5];
|
||||
int target = 9;
|
||||
|
||||
List<List<int>> res = subsetSumII(nums, target);
|
||||
|
||||
print("Input array nums = $nums, target = $target");
|
||||
print("All subsets with sum equal to $target res = $res");
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* File: iteration.dart
|
||||
* Created Time: 2023-08-27
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* for loop */
|
||||
int forLoop(int n) {
|
||||
int res = 0;
|
||||
// Sum 1, 2, ..., n-1, n
|
||||
for (int i = 1; i <= n; i++) {
|
||||
res += i;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* while loop */
|
||||
int whileLoop(int n) {
|
||||
int res = 0;
|
||||
int i = 1; // Initialize condition variable
|
||||
// Sum 1, 2, ..., n-1, n
|
||||
while (i <= n) {
|
||||
res += i;
|
||||
i++; // Update condition variable
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* while loop (two updates) */
|
||||
int whileLoopII(int n) {
|
||||
int res = 0;
|
||||
int i = 1; // Initialize condition variable
|
||||
// Sum 1, 4, 10, ...
|
||||
while (i <= n) {
|
||||
res += i;
|
||||
// Update condition variable
|
||||
i++;
|
||||
i *= 2;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Nested for loop */
|
||||
String nestedForLoop(int n) {
|
||||
String res = "";
|
||||
// Loop i = 1, 2, ..., n-1, n
|
||||
for (int i = 1; i <= n; i++) {
|
||||
// Loop j = 1, 2, ..., n-1, n
|
||||
for (int j = 1; j <= n; j++) {
|
||||
res += "($i, $j), ";
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
int n = 5;
|
||||
int res;
|
||||
|
||||
res = forLoop(n);
|
||||
print("\nFor loop sum result res = $res");
|
||||
|
||||
res = whileLoop(n);
|
||||
print("\nWhile loop sum result res = $res");
|
||||
|
||||
res = whileLoopII(n);
|
||||
print("\nWhile loop (two updates) sum result res = $res");
|
||||
|
||||
String resStr = nestedForLoop(n);
|
||||
print("\nNested for loop result $resStr");
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* File: recursion.dart
|
||||
* Created Time: 2023-08-27
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Recursion */
|
||||
int recur(int n) {
|
||||
// Termination condition
|
||||
if (n == 1) return 1;
|
||||
// Recurse: recursive call
|
||||
int res = recur(n - 1);
|
||||
// Return: return result
|
||||
return n + res;
|
||||
}
|
||||
|
||||
/* Simulate recursion using iteration */
|
||||
int forLoopRecur(int n) {
|
||||
// Use an explicit stack to simulate the system call stack
|
||||
List<int> stack = [];
|
||||
int res = 0;
|
||||
// Recurse: recursive call
|
||||
for (int i = n; i > 0; i--) {
|
||||
// Simulate "recurse" with "push"
|
||||
stack.add(i);
|
||||
}
|
||||
// Return: return result
|
||||
while (!stack.isEmpty) {
|
||||
// Simulate "return" with "pop"
|
||||
res += stack.removeLast();
|
||||
}
|
||||
// res = 1+2+3+...+n
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Tail recursion */
|
||||
int tailRecur(int n, int res) {
|
||||
// Termination condition
|
||||
if (n == 0) return res;
|
||||
// Tail recursive call
|
||||
return tailRecur(n - 1, res + n);
|
||||
}
|
||||
|
||||
/* Fibonacci sequence: recursion */
|
||||
int fib(int n) {
|
||||
// Termination condition f(1) = 0, f(2) = 1
|
||||
if (n == 1 || n == 2) return n - 1;
|
||||
// Recursive call f(n) = f(n-1) + f(n-2)
|
||||
int res = fib(n - 1) + fib(n - 2);
|
||||
// Return result f(n)
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
int n = 5;
|
||||
int res;
|
||||
|
||||
res = recur(n);
|
||||
print("\nRecursion sum result res = $res");
|
||||
|
||||
res = tailRecur(n, 0);
|
||||
print("\nTail recursion sum result res = $res");
|
||||
|
||||
res = forLoopRecur(n);
|
||||
print("\nUsing iteration to simulate recursion sum result res = $res");
|
||||
|
||||
res = fib(n);
|
||||
print("\nThe ${n}th Fibonacci number is $res");
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* File: space_complexity.dart
|
||||
* Created Time: 2023-2-12
|
||||
* Author: Jefferson (JeffersonHuang77@gmail.com)
|
||||
*/
|
||||
|
||||
// ignore_for_file: unused_local_variable
|
||||
|
||||
import 'dart:collection';
|
||||
import '../utils/list_node.dart';
|
||||
import '../utils/print_util.dart';
|
||||
import '../utils/tree_node.dart';
|
||||
|
||||
/* Function */
|
||||
int function() {
|
||||
// Perform some operations
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Constant order */
|
||||
void constant(int n) {
|
||||
// Constants, variables, objects occupy O(1) space
|
||||
final int a = 0;
|
||||
int b = 0;
|
||||
List<int> nums = List.filled(10000, 0);
|
||||
ListNode node = ListNode(0);
|
||||
// Variables in the loop occupy O(1) space
|
||||
for (var i = 0; i < n; i++) {
|
||||
int c = 0;
|
||||
}
|
||||
// Functions in the loop occupy O(1) space
|
||||
for (var i = 0; i < n; i++) {
|
||||
function();
|
||||
}
|
||||
}
|
||||
|
||||
/* Linear order */
|
||||
void linear(int n) {
|
||||
// Array of length n uses O(n) space
|
||||
List<int> nums = List.filled(n, 0);
|
||||
// A list of length n occupies O(n) space
|
||||
List<ListNode> nodes = [];
|
||||
for (var i = 0; i < n; i++) {
|
||||
nodes.add(ListNode(i));
|
||||
}
|
||||
// A hash table of length n occupies O(n) space
|
||||
Map<int, String> map = HashMap();
|
||||
for (var i = 0; i < n; i++) {
|
||||
map.putIfAbsent(i, () => i.toString());
|
||||
}
|
||||
}
|
||||
|
||||
/* Linear order (recursive implementation) */
|
||||
void linearRecur(int n) {
|
||||
print('Recursion n = $n');
|
||||
if (n == 1) return;
|
||||
linearRecur(n - 1);
|
||||
}
|
||||
|
||||
/* Exponential order */
|
||||
void quadratic(int n) {
|
||||
// Matrix uses O(n^2) space
|
||||
List<List<int>> numMatrix = List.generate(n, (_) => List.filled(n, 0));
|
||||
// 2D list uses O(n^2) space
|
||||
List<List<int>> numList = [];
|
||||
for (var i = 0; i < n; i++) {
|
||||
List<int> tmp = [];
|
||||
for (int j = 0; j < n; j++) {
|
||||
tmp.add(0);
|
||||
}
|
||||
numList.add(tmp);
|
||||
}
|
||||
}
|
||||
|
||||
/* Quadratic order (recursive implementation) */
|
||||
int quadraticRecur(int n) {
|
||||
if (n <= 0) return 0;
|
||||
List<int> nums = List.filled(n, 0);
|
||||
print('In recursion n = $n, nums length = ${nums.length}');
|
||||
return quadraticRecur(n - 1);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
TreeNode? buildTree(int n) {
|
||||
if (n == 0) return null;
|
||||
TreeNode root = TreeNode(0);
|
||||
root.left = buildTree(n - 1);
|
||||
root.right = buildTree(n - 1);
|
||||
return root;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
int n = 5;
|
||||
// Constant order
|
||||
constant(n);
|
||||
// Linear order
|
||||
linear(n);
|
||||
linearRecur(n);
|
||||
// Exponential order
|
||||
quadratic(n);
|
||||
quadraticRecur(n);
|
||||
// Exponential order
|
||||
TreeNode? root = buildTree(n);
|
||||
printTree(root);
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
/**
|
||||
* File: time_complexity.dart
|
||||
* Created Time: 2023-02-12
|
||||
* Author: Jefferson (JeffersonHuang77@gmail.com)
|
||||
*/
|
||||
|
||||
// ignore_for_file: unused_local_variable
|
||||
|
||||
/* Constant order */
|
||||
int constant(int n) {
|
||||
int count = 0;
|
||||
int size = 100000;
|
||||
for (var i = 0; i < size; i++) {
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Linear order */
|
||||
int linear(int n) {
|
||||
int count = 0;
|
||||
for (var i = 0; i < n; i++) {
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Linear order (traversing array) */
|
||||
int arrayTraversal(List<int> nums) {
|
||||
int count = 0;
|
||||
// Number of iterations is proportional to the array length
|
||||
for (var _num in nums) {
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Exponential order */
|
||||
int quadratic(int n) {
|
||||
int count = 0;
|
||||
// Number of iterations is quadratically related to the data size n
|
||||
for (int i = 0; i < n; i++) {
|
||||
for (int j = 0; j < n; j++) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Quadratic order (bubble sort) */
|
||||
int bubbleSort(List<int> nums) {
|
||||
int count = 0; // Counter
|
||||
// Outer loop: unsorted range is [0, i]
|
||||
for (var i = nums.length - 1; i > 0; i--) {
|
||||
// Inner loop: swap the largest element in the unsorted range [0, i] to the rightmost end of that range
|
||||
for (var 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
|
||||
}
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Exponential order (loop 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)
|
||||
for (var i = 0; i < n; i++) {
|
||||
for (var j = 0; j < base; j++) {
|
||||
count++;
|
||||
}
|
||||
base *= 2;
|
||||
}
|
||||
// count = 1 + 2 + 4 + 8 + .. + 2^(n-1) = 2^n - 1
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Exponential order (recursive implementation) */
|
||||
int expRecur(int n) {
|
||||
if (n == 1) return 1;
|
||||
return expRecur(n - 1) + expRecur(n - 1) + 1;
|
||||
}
|
||||
|
||||
/* Logarithmic order (loop implementation) */
|
||||
int logarithmic(int n) {
|
||||
int count = 0;
|
||||
while (n > 1) {
|
||||
n = n ~/ 2;
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Logarithmic order (recursive implementation) */
|
||||
int logRecur(int n) {
|
||||
if (n <= 1) return 0;
|
||||
return logRecur(n ~/ 2) + 1;
|
||||
}
|
||||
|
||||
/* Linearithmic order */
|
||||
int linearLogRecur(int n) {
|
||||
if (n <= 1) return 1;
|
||||
int count = linearLogRecur(n ~/ 2) + linearLogRecur(n ~/ 2);
|
||||
for (var i = 0; i < n; i++) {
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Factorial order (recursive implementation) */
|
||||
int factorialRecur(int n) {
|
||||
if (n == 0) return 1;
|
||||
int count = 0;
|
||||
// Split from 1 into n
|
||||
for (var i = 0; i < n; i++) {
|
||||
count += factorialRecur(n - 1);
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
// You can modify n to run and observe the trend of the number of operations for various complexities
|
||||
int n = 8;
|
||||
print('Input data size n = $n');
|
||||
|
||||
int count = constant(n);
|
||||
print('Constant-time operations count = $count');
|
||||
|
||||
count = linear(n);
|
||||
print('Linear-time operations count = $count');
|
||||
|
||||
count = arrayTraversal(List.filled(n, 0));
|
||||
print('Linear-time (array traversal) operations count = $count');
|
||||
|
||||
count = quadratic(n);
|
||||
print('Quadratic-time operations count = $count');
|
||||
final nums = List.filled(n, 0);
|
||||
for (int i = 0; i < n; i++) {
|
||||
nums[i] = n - i; // [n,n-1,...,2,1]
|
||||
}
|
||||
count = bubbleSort(nums);
|
||||
print('Quadratic-time (bubble sort) operations count = $count');
|
||||
|
||||
count = exponential(n);
|
||||
print('Exponential-time (iterative) operations count = $count');
|
||||
count = expRecur(n);
|
||||
print('Exponential-time (recursive) operations count = $count');
|
||||
|
||||
count = logarithmic(n);
|
||||
print('Logarithmic-time (iterative) operations count = $count');
|
||||
count = logRecur(n);
|
||||
print('Logarithmic-time (recursive) operations count = $count');
|
||||
|
||||
count = linearLogRecur(n);
|
||||
print('Linearithmic-time (recursive) operations count = $count');
|
||||
|
||||
count = factorialRecur(n);
|
||||
print('Factorial-time (recursive) operations count = $count');
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* File: worst_best_time_complexity.dart
|
||||
* Created Time: 2023-02-12
|
||||
* Author: Jefferson (JeffersonHuang77@gmail.com)
|
||||
*/
|
||||
|
||||
/* Generate an array with elements { 1, 2, ..., n }, order shuffled */
|
||||
List<int> randomNumbers(int n) {
|
||||
final nums = List.filled(n, 0);
|
||||
// Generate array nums = { 1, 2, 3, ..., n }
|
||||
for (var i = 0; i < n; i++) {
|
||||
nums[i] = i + 1;
|
||||
}
|
||||
// Randomly shuffle array elements
|
||||
nums.shuffle();
|
||||
|
||||
return nums;
|
||||
}
|
||||
|
||||
/* Find the index of number 1 in array nums */
|
||||
int findOne(List<int> nums) {
|
||||
for (var i = 0; i < nums.length; 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
|
||||
if (nums[i] == 1) return i;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
for (var i = 0; i < 10; i++) {
|
||||
int n = 100;
|
||||
final nums = randomNumbers(n);
|
||||
int index = findOne(nums);
|
||||
print('\nArray [ 1, 2, ..., n ] after shuffling = $nums');
|
||||
print('Index of number 1 is + $index');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* File: binary_search_recur.dart
|
||||
* Created Time: 2023-08-10
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Binary search: problem f(i, j) */
|
||||
int dfs(List<int> nums, int target, int i, int j) {
|
||||
// If the interval is empty, it means there is no target element, 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)
|
||||
return dfs(nums, target, m + 1, j);
|
||||
} else if (nums[m] > target) {
|
||||
// Recursion subproblem f(i, m-1)
|
||||
return dfs(nums, target, i, m - 1);
|
||||
} else {
|
||||
// Found the target element, return its index
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/* Binary search */
|
||||
int binarySearch(List<int> nums, int target) {
|
||||
int n = nums.length;
|
||||
// Solve the problem f(0, n-1)
|
||||
return dfs(nums, target, 0, n - 1);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
int target = 6;
|
||||
List<int> nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35];
|
||||
|
||||
// Binary search (closed interval on both sides)
|
||||
int index = binarySearch(nums, target);
|
||||
print("Index of target element 6 = $index");
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* File: build_tree.dart
|
||||
* Created Time: 2023-08-10
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import '../utils/print_util.dart';
|
||||
import '../utils/tree_node.dart';
|
||||
|
||||
/* Build binary tree: divide and conquer */
|
||||
TreeNode? dfs(
|
||||
List<int> preorder,
|
||||
Map<int, int> inorderMap,
|
||||
int i,
|
||||
int l,
|
||||
int r,
|
||||
) {
|
||||
// Terminate when the subtree interval is empty
|
||||
if (r - l < 0) {
|
||||
return null;
|
||||
}
|
||||
// Initialize the root node
|
||||
TreeNode? root = TreeNode(preorder[i]);
|
||||
// Query m to divide 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);
|
||||
// Subproblem: build the right subtree
|
||||
root.right = dfs(preorder, inorderMap, i + 1 + m - l, m + 1, r);
|
||||
// Return the root node
|
||||
return root;
|
||||
}
|
||||
|
||||
/* Build binary tree */
|
||||
TreeNode? buildTree(List<int> preorder, List<int> inorder) {
|
||||
// Initialize hash map, storing the mapping from inorder elements to indices
|
||||
Map<int, int> inorderMap = {};
|
||||
for (int i = 0; i < inorder.length; i++) {
|
||||
inorderMap[inorder[i]] = i;
|
||||
}
|
||||
TreeNode? root = dfs(preorder, inorderMap, 0, 0, inorder.length - 1);
|
||||
return root;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
List<int> preorder = [3, 9, 2, 1, 7];
|
||||
List<int> inorder = [9, 3, 1, 2, 7];
|
||||
print("Pre-order traversal = $preorder");
|
||||
print("In-order traversal = $inorder");
|
||||
|
||||
TreeNode? root = buildTree(preorder, inorder);
|
||||
print("The constructed binary tree is:");
|
||||
printTree(root!);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* File: hanota.dart
|
||||
* Created Time: 2023-08-10
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Move a disk */
|
||||
void move(List<int> src, List<int> tar) {
|
||||
// Take out a disk from the top of src
|
||||
int pan = src.removeLast();
|
||||
// Place the disk on top of tar
|
||||
tar.add(pan);
|
||||
}
|
||||
|
||||
/* Solve the Tower of Hanoi problem f(i) */
|
||||
void dfs(int i, List<int> src, List<int> buf, List<int> tar) {
|
||||
// If there is only one disk left in src, move it directly to tar
|
||||
if (i == 1) {
|
||||
move(src, tar);
|
||||
return;
|
||||
}
|
||||
// Subproblem f(i-1): move the top i-1 disks from src to buf using tar
|
||||
dfs(i - 1, src, tar, buf);
|
||||
// Subproblem f(1): move the remaining disk 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);
|
||||
}
|
||||
|
||||
/* Solve the Tower of Hanoi problem */
|
||||
void solveHanota(List<int> A, List<int> B, List<int> C) {
|
||||
int n = A.length;
|
||||
// Move the top n disks from A to C using B
|
||||
dfs(n, A, B, C);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
// The tail of the list is the top of the rod
|
||||
List<int> A = [5, 4, 3, 2, 1];
|
||||
List<int> B = [];
|
||||
List<int> C = [];
|
||||
print("In initial state:");
|
||||
print("A = $A");
|
||||
print("B = $B");
|
||||
print("C = $C");
|
||||
|
||||
solveHanota(A, B, C);
|
||||
|
||||
print("After disk movement is complete:");
|
||||
print("A = $A");
|
||||
print("B = $B");
|
||||
print("C = $C");
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* File: climbing_stairs_backtrack.dart
|
||||
* Created Time: 2023-08-11
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking */
|
||||
void backtrack(List<int> choices, int state, int n, List<int> res) {
|
||||
// When climbing to the n-th stair, add 1 to the solution count
|
||||
if (state == n) {
|
||||
res[0]++;
|
||||
}
|
||||
// Traverse all choices
|
||||
for (int choice in choices) {
|
||||
// Pruning: not allowed to go beyond the n-th stair
|
||||
if (state + choice > n) continue;
|
||||
// Attempt: make choice, update state
|
||||
backtrack(choices, state + choice, n, res);
|
||||
// Backtrack
|
||||
}
|
||||
}
|
||||
|
||||
/* Climbing stairs: Backtracking */
|
||||
int climbingStairsBacktrack(int n) {
|
||||
List<int> choices = [1, 2]; // Can choose to climb up 1 or 2 stairs
|
||||
int state = 0; // Start climbing from the 0-th stair
|
||||
List<int> res = [];
|
||||
res.add(0); // Use res[0] to record the solution count
|
||||
backtrack(choices, state, n, res);
|
||||
return res[0];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsBacktrack(n);
|
||||
print("Climbing $n stairs has $res solutions");
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* File: climbing_stairs_constraint_dp.dart
|
||||
* Created Time: 2023-08-11
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Climbing stairs with constraint: Dynamic programming */
|
||||
int climbingStairsConstraintDP(int n) {
|
||||
if (n == 1 || n == 2) {
|
||||
return 1;
|
||||
}
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
List<List<int>> dp = List.generate(n + 1, (index) => List.filled(3, 0));
|
||||
// Initial state: preset the solution to the smallest subproblem
|
||||
dp[1][1] = 1;
|
||||
dp[1][2] = 0;
|
||||
dp[2][1] = 0;
|
||||
dp[2][2] = 1;
|
||||
// State transition: gradually solve larger subproblems from smaller ones
|
||||
for (int i = 3; i <= n; i++) {
|
||||
dp[i][1] = dp[i - 1][2];
|
||||
dp[i][2] = dp[i - 2][1] + dp[i - 2][2];
|
||||
}
|
||||
return dp[n][1] + dp[n][2];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsConstraintDP(n);
|
||||
print("Climbing $n stairs has $res solutions");
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* File: climbing_stairs_dfs.dart
|
||||
* Created Time: 2023-08-11
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Search */
|
||||
int dfs(int i) {
|
||||
// Known dp[1] and dp[2], return them
|
||||
if (i == 1 || i == 2) return i;
|
||||
// dp[i] = dp[i-1] + dp[i-2]
|
||||
int count = dfs(i - 1) + dfs(i - 2);
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Climbing stairs: Search */
|
||||
int climbingStairsDFS(int n) {
|
||||
return dfs(n);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsDFS(n);
|
||||
print("Climbing $n stairs has $res solutions");
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* File: climbing_stairs_dfs_mem.dart
|
||||
* Created Time: 2023-08-11
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Memoization search */
|
||||
int dfs(int i, List<int> mem) {
|
||||
// Known dp[1] and dp[2], return them
|
||||
if (i == 1 || i == 2) return i;
|
||||
// If record dp[i] exists, return it directly
|
||||
if (mem[i] != -1) return mem[i];
|
||||
// dp[i] = dp[i-1] + dp[i-2]
|
||||
int count = dfs(i - 1, mem) + dfs(i - 2, mem);
|
||||
// Record dp[i]
|
||||
mem[i] = count;
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Climbing stairs: Memoization search */
|
||||
int climbingStairsDFSMem(int n) {
|
||||
// mem[i] records the total number of solutions to climb to the i-th stair, -1 means no record
|
||||
List<int> mem = List.filled(n + 1, -1);
|
||||
return dfs(n, mem);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsDFSMem(n);
|
||||
print("Climbing $n stairs has $res solutions");
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* File: climbing_stairs_dp.dart
|
||||
* Created Time: 2023-08-11
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Climbing stairs: Dynamic programming */
|
||||
int climbingStairsDP(int n) {
|
||||
if (n == 1 || n == 2) return n;
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
List<int> dp = List.filled(n + 1, 0);
|
||||
// Initial state: preset the solution to the smallest subproblem
|
||||
dp[1] = 1;
|
||||
dp[2] = 2;
|
||||
// State transition: gradually solve larger subproblems from smaller ones
|
||||
for (int i = 3; i <= n; i++) {
|
||||
dp[i] = dp[i - 1] + dp[i - 2];
|
||||
}
|
||||
return dp[n];
|
||||
}
|
||||
|
||||
/* Climbing stairs: Space-optimized dynamic programming */
|
||||
int climbingStairsDPComp(int n) {
|
||||
if (n == 1 || n == 2) return n;
|
||||
int a = 1, b = 2;
|
||||
for (int i = 3; i <= n; i++) {
|
||||
int tmp = b;
|
||||
b = a + b;
|
||||
a = tmp;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsDP(n);
|
||||
print("Climbing $n stairs has $res solutions");
|
||||
|
||||
res = climbingStairsDPComp(n);
|
||||
print("Climbing $n stairs has $res solutions");
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* File: coin_change.dart
|
||||
* Created Time: 2023-08-11
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
/* Coin change: Dynamic programming */
|
||||
int coinChangeDP(List<int> coins, int amt) {
|
||||
int n = coins.length;
|
||||
int MAX = amt + 1;
|
||||
// Initialize dp table
|
||||
List<List<int>> dp = List.generate(n + 1, (index) => List.filled(amt + 1, 0));
|
||||
// State transition: first row and first column
|
||||
for (int a = 1; a <= amt; a++) {
|
||||
dp[0][a] = MAX;
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// If exceeds target amount, don't select coin i
|
||||
dp[i][a] = dp[i - 1][a];
|
||||
} else {
|
||||
// The smaller value between not selecting and selecting coin i
|
||||
dp[i][a] = min(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][amt] != MAX ? dp[n][amt] : -1;
|
||||
}
|
||||
|
||||
/* Coin change: Space-optimized dynamic programming */
|
||||
int coinChangeDPComp(List<int> coins, int amt) {
|
||||
int n = coins.length;
|
||||
int MAX = amt + 1;
|
||||
// Initialize dp table
|
||||
List<int> dp = List.filled(amt + 1, MAX);
|
||||
dp[0] = 0;
|
||||
// State transition
|
||||
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
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// The smaller value between not selecting and selecting coin i
|
||||
dp[a] = min(dp[a], dp[a - coins[i - 1]] + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[amt] != MAX ? dp[amt] : -1;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
List<int> coins = [1, 2, 5];
|
||||
int amt = 4;
|
||||
|
||||
// Dynamic programming
|
||||
int res = coinChangeDP(coins, amt);
|
||||
print("Minimum coins needed to make target amount is $res");
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = coinChangeDPComp(coins, amt);
|
||||
print("Minimum coins needed to make target amount is $res");
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* File: coin_change_ii.dart
|
||||
* Created Time: 2023-08-11
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Coin change II: Dynamic programming */
|
||||
int coinChangeIIDP(List<int> coins, int amt) {
|
||||
int n = coins.length;
|
||||
// Initialize dp table
|
||||
List<List<int>> dp = List.generate(n + 1, (index) => List.filled(amt + 1, 0));
|
||||
// Initialize first column
|
||||
for (int i = 0; i <= n; i++) {
|
||||
dp[i][0] = 1;
|
||||
}
|
||||
// State transition
|
||||
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
|
||||
dp[i][a] = dp[i - 1][a];
|
||||
} else {
|
||||
// Sum of the two options: not selecting and selecting coin i
|
||||
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]];
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][amt];
|
||||
}
|
||||
|
||||
/* Coin change II: Space-optimized dynamic programming */
|
||||
int coinChangeIIDPComp(List<int> coins, int amt) {
|
||||
int n = coins.length;
|
||||
// Initialize dp table
|
||||
List<int> dp = List.filled(amt + 1, 0);
|
||||
dp[0] = 1;
|
||||
// State transition
|
||||
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
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// Sum of the two options: not selecting and selecting coin i
|
||||
dp[a] = dp[a] + dp[a - coins[i - 1]];
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[amt];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
List<int> coins = [1, 2, 5];
|
||||
int amt = 5;
|
||||
|
||||
// Dynamic programming
|
||||
int res = coinChangeIIDP(coins, amt);
|
||||
print("Number of coin combinations to make target amount is $res");
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = coinChangeIIDPComp(coins, amt);
|
||||
print("Number of coin combinations to make target amount is $res");
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* File: edit_distance.dart
|
||||
* Created Time: 2023-08-11
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
/* Edit distance: Brute-force search */
|
||||
int editDistanceDFS(String s, String t, int i, int j) {
|
||||
// If both s and t are empty, return 0
|
||||
if (i == 0 && j == 0) return 0;
|
||||
// If s is empty, return length of t
|
||||
if (i == 0) return j;
|
||||
// If t is empty, return length of s
|
||||
if (j == 0) return i;
|
||||
// If two characters are equal, skip both characters
|
||||
if (s[i - 1] == t[j - 1]) return editDistanceDFS(s, t, i - 1, j - 1);
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
int insert = editDistanceDFS(s, t, i, j - 1);
|
||||
int delete = editDistanceDFS(s, t, i - 1, j);
|
||||
int replace = editDistanceDFS(s, t, i - 1, j - 1);
|
||||
// Return minimum edit steps
|
||||
return min(min(insert, delete), replace) + 1;
|
||||
}
|
||||
|
||||
/* Edit distance: Memoization search */
|
||||
int editDistanceDFSMem(String s, String t, List<List<int>> mem, int i, int j) {
|
||||
// If both s and t are empty, return 0
|
||||
if (i == 0 && j == 0) return 0;
|
||||
// If s is empty, return length of t
|
||||
if (i == 0) return j;
|
||||
// If t is empty, return length of s
|
||||
if (j == 0) return i;
|
||||
// If there's a record, return it directly
|
||||
if (mem[i][j] != -1) return mem[i][j];
|
||||
// If two characters are equal, skip both characters
|
||||
if (s[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
|
||||
int insert = editDistanceDFSMem(s, t, mem, i, j - 1);
|
||||
int delete = editDistanceDFSMem(s, t, mem, i - 1, j);
|
||||
int replace = editDistanceDFSMem(s, t, mem, i - 1, j - 1);
|
||||
// Record and return minimum edit steps
|
||||
mem[i][j] = min(min(insert, delete), replace) + 1;
|
||||
return mem[i][j];
|
||||
}
|
||||
|
||||
/* Edit distance: Dynamic programming */
|
||||
int editDistanceDP(String s, String t) {
|
||||
int n = s.length, m = t.length;
|
||||
List<List<int>> dp = List.generate(n + 1, (_) => List.filled(m + 1, 0));
|
||||
// State transition: 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
|
||||
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
|
||||
dp[i][j] = dp[i - 1][j - 1];
|
||||
} else {
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
dp[i][j] = min(min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][m];
|
||||
}
|
||||
|
||||
/* Edit distance: Space-optimized dynamic programming */
|
||||
int editDistanceDPComp(String s, String t) {
|
||||
int n = s.length, m = t.length;
|
||||
List<int> dp = List.filled(m + 1, 0);
|
||||
// State transition: first row
|
||||
for (int j = 1; j <= m; j++) {
|
||||
dp[j] = j;
|
||||
}
|
||||
// State transition: rest of the rows
|
||||
for (int i = 1; i <= n; i++) {
|
||||
// State transition: first column
|
||||
int leftup = dp[0]; // Temporarily store dp[i-1, j-1]
|
||||
dp[0] = i;
|
||||
// State transition: rest of the 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
|
||||
dp[j] = leftup;
|
||||
} else {
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
dp[j] = min(min(dp[j - 1], dp[j]), leftup) + 1;
|
||||
}
|
||||
leftup = temp; // Update for next round's dp[i-1, j-1]
|
||||
}
|
||||
}
|
||||
return dp[m];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
String s = "bag";
|
||||
String t = "pack";
|
||||
int n = s.length, m = t.length;
|
||||
|
||||
// Brute-force search
|
||||
int res = editDistanceDFS(s, t, n, m);
|
||||
print("Changing " + s + " to " + t + " requires minimum $res edits");
|
||||
|
||||
// Memoization search
|
||||
List<List<int>> mem = List.generate(n + 1, (_) => List.filled(m + 1, -1));
|
||||
res = editDistanceDFSMem(s, t, mem, n, m);
|
||||
print("Changing " + s + " to " + t + " requires minimum $res edits");
|
||||
|
||||
// Dynamic programming
|
||||
res = editDistanceDP(s, t);
|
||||
print("Changing " + s + " to " + t + " requires minimum $res edits");
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = editDistanceDPComp(s, t);
|
||||
print("Changing " + s + " to " + t + " requires minimum $res edits");
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* File: knapsack.dart
|
||||
* Created Time: 2023-08-11
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
/* 0-1 knapsack: Brute-force search */
|
||||
int knapsackDFS(List<int> wgt, List<int> val, int i, int c) {
|
||||
// If all items have been selected or knapsack has no remaining capacity, return value 0
|
||||
if (i == 0 || c == 0) {
|
||||
return 0;
|
||||
}
|
||||
// If exceeds knapsack capacity, can only choose not to put it in
|
||||
if (wgt[i - 1] > c) {
|
||||
return knapsackDFS(wgt, val, i - 1, c);
|
||||
}
|
||||
// Calculate the maximum value of not putting in and putting in item i
|
||||
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 max(no, yes);
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Memoization search */
|
||||
int knapsackDFSMem(
|
||||
List<int> wgt,
|
||||
List<int> val,
|
||||
List<List<int>> mem,
|
||||
int i,
|
||||
int c,
|
||||
) {
|
||||
// If all items have been selected or knapsack has no remaining capacity, return value 0
|
||||
if (i == 0 || c == 0) {
|
||||
return 0;
|
||||
}
|
||||
// If there's a record, return it directly
|
||||
if (mem[i][c] != -1) {
|
||||
return mem[i][c];
|
||||
}
|
||||
// If exceeds knapsack capacity, can only choose not to put it in
|
||||
if (wgt[i - 1] > c) {
|
||||
return knapsackDFSMem(wgt, val, mem, i - 1, c);
|
||||
}
|
||||
// Calculate the maximum value of not putting in and putting in item i
|
||||
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
|
||||
mem[i][c] = max(no, yes);
|
||||
return mem[i][c];
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Dynamic programming */
|
||||
int knapsackDP(List<int> wgt, List<int> val, int cap) {
|
||||
int n = wgt.length;
|
||||
// Initialize dp table
|
||||
List<List<int>> dp = List.generate(n + 1, (index) => List.filled(cap + 1, 0));
|
||||
// State transition
|
||||
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
|
||||
dp[i][c] = dp[i - 1][c];
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
dp[i][c] = max(dp[i - 1][c], dp[i - 1][c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][cap];
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Space-optimized dynamic programming */
|
||||
int knapsackDPComp(List<int> wgt, List<int> val, int cap) {
|
||||
int n = wgt.length;
|
||||
// Initialize dp table
|
||||
List<int> dp = List.filled(cap + 1, 0);
|
||||
// State transition
|
||||
for (int i = 1; i <= n; i++) {
|
||||
// Traverse in reverse order
|
||||
for (int c = cap; c >= 1; c--) {
|
||||
if (wgt[i - 1] <= c) {
|
||||
// The larger value between not selecting and selecting item i
|
||||
dp[c] = max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
List<int> wgt = [10, 20, 30, 40, 50];
|
||||
List<int> val = [50, 120, 150, 210, 240];
|
||||
int cap = 50;
|
||||
int n = wgt.length;
|
||||
|
||||
// Brute-force search
|
||||
int res = knapsackDFS(wgt, val, n, cap);
|
||||
print("Maximum item value not exceeding knapsack capacity is $res");
|
||||
|
||||
// Memoization search
|
||||
List<List<int>> mem =
|
||||
List.generate(n + 1, (index) => List.filled(cap + 1, -1));
|
||||
res = knapsackDFSMem(wgt, val, mem, n, cap);
|
||||
print("Maximum item value not exceeding knapsack capacity is $res");
|
||||
|
||||
// Dynamic programming
|
||||
res = knapsackDP(wgt, val, cap);
|
||||
print("Maximum item value not exceeding knapsack capacity is $res");
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = knapsackDPComp(wgt, val, cap);
|
||||
print("Maximum item value not exceeding knapsack capacity is $res");
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* File: min_cost_climbing_stairs_dp.dart
|
||||
* Created Time: 2023-08-11
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
/* Minimum cost climbing stairs: Dynamic programming */
|
||||
int minCostClimbingStairsDP(List<int> cost) {
|
||||
int n = cost.length - 1;
|
||||
if (n == 1 || n == 2) return cost[n];
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
List<int> dp = List.filled(n + 1, 0);
|
||||
// Initial state: preset the solution to the smallest subproblem
|
||||
dp[1] = cost[1];
|
||||
dp[2] = cost[2];
|
||||
// State transition: gradually solve larger subproblems from smaller ones
|
||||
for (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 */
|
||||
int minCostClimbingStairsDPComp(List<int> cost) {
|
||||
int n = cost.length - 1;
|
||||
if (n == 1 || n == 2) return cost[n];
|
||||
int a = cost[1], b = cost[2];
|
||||
for (int i = 3; i <= n; i++) {
|
||||
int tmp = b;
|
||||
b = min(a, tmp) + cost[i];
|
||||
a = tmp;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
List<int> cost = [0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1];
|
||||
print("Input stair cost list is $cost");
|
||||
|
||||
int res = minCostClimbingStairsDP(cost);
|
||||
print("Minimum cost to climb stairs is $res");
|
||||
|
||||
res = minCostClimbingStairsDPComp(cost);
|
||||
print("Minimum cost to climb stairs is $res");
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* File: min_path_sum.dart
|
||||
* Created Time: 2023-08-11
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
/* Minimum path sum: Brute-force search */
|
||||
int minPathSumDFS(List<List<int>> grid, int i, int j) {
|
||||
// If it's the top-left cell, terminate the search
|
||||
if (i == 0 && j == 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// If row or column index is out of bounds, return +∞ cost
|
||||
if (i < 0 || j < 0) {
|
||||
// In Dart, int type is fixed-range integer, no value representing "infinity"
|
||||
return BigInt.from(2).pow(31).toInt();
|
||||
}
|
||||
// Calculate the minimum path cost from top-left to (i-1, j) and (i, j-1)
|
||||
int up = minPathSumDFS(grid, i - 1, j);
|
||||
int left = minPathSumDFS(grid, i, j - 1);
|
||||
// Return the minimum path cost from top-left to (i, j)
|
||||
return min(left, up) + grid[i][j];
|
||||
}
|
||||
|
||||
/* Minimum path sum: Memoization search */
|
||||
int minPathSumDFSMem(List<List<int>> grid, List<List<int>> mem, int i, int j) {
|
||||
// If it's the top-left cell, terminate the search
|
||||
if (i == 0 && j == 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// If row or column index is out of bounds, return +∞ cost
|
||||
if (i < 0 || j < 0) {
|
||||
// In Dart, int type is fixed-range integer, no value representing "infinity"
|
||||
return BigInt.from(2).pow(31).toInt();
|
||||
}
|
||||
// If there's a record, return it directly
|
||||
if (mem[i][j] != -1) {
|
||||
return mem[i][j];
|
||||
}
|
||||
// Minimum path cost for left and upper cells
|
||||
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)
|
||||
mem[i][j] = min(left, up) + grid[i][j];
|
||||
return mem[i][j];
|
||||
}
|
||||
|
||||
/* Minimum path sum: Dynamic programming */
|
||||
int minPathSumDP(List<List<int>> grid) {
|
||||
int n = grid.length, m = grid[0].length;
|
||||
// Initialize dp table
|
||||
List<List<int>> dp = List.generate(n, (i) => List.filled(m, 0));
|
||||
dp[0][0] = grid[0][0];
|
||||
// State transition: first row
|
||||
for (int j = 1; j < m; j++) {
|
||||
dp[0][j] = dp[0][j - 1] + grid[0][j];
|
||||
}
|
||||
// State transition: 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
|
||||
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];
|
||||
}
|
||||
}
|
||||
return dp[n - 1][m - 1];
|
||||
}
|
||||
|
||||
/* Minimum path sum: Space-optimized dynamic programming */
|
||||
int minPathSumDPComp(List<List<int>> grid) {
|
||||
int n = grid.length, m = grid[0].length;
|
||||
// Initialize dp table
|
||||
List<int> dp = List.filled(m, 0);
|
||||
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
|
||||
for (int i = 1; i < n; i++) {
|
||||
// State transition: first column
|
||||
dp[0] = dp[0] + grid[i][0];
|
||||
// State transition: rest of the columns
|
||||
for (int j = 1; j < m; j++) {
|
||||
dp[j] = min(dp[j - 1], dp[j]) + grid[i][j];
|
||||
}
|
||||
}
|
||||
return dp[m - 1];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
List<List<int>> grid = [
|
||||
[1, 3, 1, 5],
|
||||
[2, 2, 4, 2],
|
||||
[5, 3, 2, 1],
|
||||
[4, 3, 5, 2],
|
||||
];
|
||||
int n = grid.length, m = grid[0].length;
|
||||
|
||||
// Brute-force search
|
||||
int res = minPathSumDFS(grid, n - 1, m - 1);
|
||||
print("Minimum path sum from top-left to bottom-right is $res");
|
||||
|
||||
// Memoization search
|
||||
List<List<int>> mem = List.generate(n, (i) => List.filled(m, -1));
|
||||
res = minPathSumDFSMem(grid, mem, n - 1, m - 1);
|
||||
print("Minimum path sum from top-left to bottom-right is $res");
|
||||
|
||||
// Dynamic programming
|
||||
res = minPathSumDP(grid);
|
||||
print("Minimum path sum from top-left to bottom-right is $res");
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = minPathSumDPComp(grid);
|
||||
print("Minimum path sum from top-left to bottom-right is $res");
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* File: unbounded_knapsack.dart
|
||||
* Created Time: 2023-08-11
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
/* Unbounded knapsack: Dynamic programming */
|
||||
int unboundedKnapsackDP(List<int> wgt, List<int> val, int cap) {
|
||||
int n = wgt.length;
|
||||
// Initialize dp table
|
||||
List<List<int>> dp = List.generate(n + 1, (index) => List.filled(cap + 1, 0));
|
||||
// State transition
|
||||
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
|
||||
dp[i][c] = dp[i - 1][c];
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
dp[i][c] = max(dp[i - 1][c], dp[i][c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][cap];
|
||||
}
|
||||
|
||||
/* Unbounded knapsack: Space-optimized dynamic programming */
|
||||
int unboundedKnapsackDPComp(List<int> wgt, List<int> val, int cap) {
|
||||
int n = wgt.length;
|
||||
// Initialize dp table
|
||||
List<int> dp = List.filled(cap + 1, 0);
|
||||
// State transition
|
||||
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
|
||||
dp[c] = dp[c];
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
dp[c] = max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
List<int> wgt = [1, 2, 3];
|
||||
List<int> val = [5, 11, 15];
|
||||
int cap = 4;
|
||||
|
||||
// Dynamic programming
|
||||
int res = unboundedKnapsackDP(wgt, val, cap);
|
||||
print("Maximum item value not exceeding knapsack capacity is $res");
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
int resComp = unboundedKnapsackDPComp(wgt, val, cap);
|
||||
print("Maximum item value not exceeding knapsack capacity is $resComp");
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* File: graph_adjacency_list.dart
|
||||
* Created Time: 2023-05-15
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import '../utils/vertex.dart';
|
||||
|
||||
/* Undirected graph class based on adjacency list */
|
||||
class GraphAdjList {
|
||||
// Adjacency list, key: vertex, value: all adjacent vertices of that vertex
|
||||
Map<Vertex, List<Vertex>> adjList = {};
|
||||
|
||||
/* Constructor */
|
||||
GraphAdjList(List<List<Vertex>> edges) {
|
||||
for (List<Vertex> edge in edges) {
|
||||
addVertex(edge[0]);
|
||||
addVertex(edge[1]);
|
||||
addEdge(edge[0], edge[1]);
|
||||
}
|
||||
}
|
||||
|
||||
/* Get the number of vertices */
|
||||
int size() {
|
||||
return adjList.length;
|
||||
}
|
||||
|
||||
/* Add edge */
|
||||
void addEdge(Vertex vet1, Vertex vet2) {
|
||||
if (!adjList.containsKey(vet1) ||
|
||||
!adjList.containsKey(vet2) ||
|
||||
vet1 == vet2) {
|
||||
throw ArgumentError;
|
||||
}
|
||||
// Add edge vet1 - vet2
|
||||
adjList[vet1]!.add(vet2);
|
||||
adjList[vet2]!.add(vet1);
|
||||
}
|
||||
|
||||
/* Remove edge */
|
||||
void removeEdge(Vertex vet1, Vertex vet2) {
|
||||
if (!adjList.containsKey(vet1) ||
|
||||
!adjList.containsKey(vet2) ||
|
||||
vet1 == vet2) {
|
||||
throw ArgumentError;
|
||||
}
|
||||
// Remove edge vet1 - vet2
|
||||
adjList[vet1]!.remove(vet2);
|
||||
adjList[vet2]!.remove(vet1);
|
||||
}
|
||||
|
||||
/* Add vertex */
|
||||
void addVertex(Vertex vet) {
|
||||
if (adjList.containsKey(vet)) return;
|
||||
// Add a new linked list in the adjacency list
|
||||
adjList[vet] = [];
|
||||
}
|
||||
|
||||
/* Remove vertex */
|
||||
void removeVertex(Vertex vet) {
|
||||
if (!adjList.containsKey(vet)) {
|
||||
throw ArgumentError;
|
||||
}
|
||||
// Remove the linked list corresponding to vertex vet in the adjacency list
|
||||
adjList.remove(vet);
|
||||
// Traverse the linked lists of other vertices and remove all edges containing vet
|
||||
adjList.forEach((key, value) {
|
||||
value.remove(vet);
|
||||
});
|
||||
}
|
||||
|
||||
/* Print adjacency list */
|
||||
void printAdjList() {
|
||||
print("Adjacency list =");
|
||||
adjList.forEach((key, value) {
|
||||
List<int> tmp = [];
|
||||
for (Vertex vertex in value) {
|
||||
tmp.add(vertex.val);
|
||||
}
|
||||
print("${key.val}: $tmp,");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
/* Add edge */
|
||||
List<Vertex> v = Vertex.valsToVets([1, 3, 2, 5, 4]);
|
||||
List<List<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 = GraphAdjList(edges);
|
||||
print("\nAfter initialization, graph is");
|
||||
graph.printAdjList();
|
||||
|
||||
/* Add edge */
|
||||
// Vertices 1, 3 are v[0], v[1]
|
||||
graph.addEdge(v[0], v[2]);
|
||||
print("\nAfter adding edge 1-2, graph is");
|
||||
graph.printAdjList();
|
||||
|
||||
/* Remove edge */
|
||||
// Vertex 3 is v[1]
|
||||
graph.removeEdge(v[0], v[1]);
|
||||
print("\nAfter removing edge 1-3, graph is");
|
||||
graph.printAdjList();
|
||||
|
||||
/* Add vertex */
|
||||
Vertex v5 = Vertex(6);
|
||||
graph.addVertex(v5);
|
||||
print("\nAfter adding vertex 6, graph is");
|
||||
graph.printAdjList();
|
||||
|
||||
/* Remove vertex */
|
||||
// Vertex 3 is v[1]
|
||||
graph.removeVertex(v[1]);
|
||||
print("\nAfter removing vertex 3, graph is");
|
||||
graph.printAdjList();
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* File: graph_adjacency_matrix.dart
|
||||
* Created Time: 2023-05-15
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import '../utils/print_util.dart';
|
||||
|
||||
/* Undirected graph class based on adjacency matrix */
|
||||
class GraphAdjMat {
|
||||
List<int> vertices = []; // Vertex elements, elements represent "vertex values", indices represent "vertex indices"
|
||||
List<List<int>> adjMat = []; // Adjacency matrix, where the row and column indices correspond to the "vertex index"
|
||||
|
||||
/* Constructor */
|
||||
GraphAdjMat(List<int> vertices, List<List<int>> edges) {
|
||||
this.vertices = [];
|
||||
this.adjMat = [];
|
||||
// Add vertex
|
||||
for (int val in vertices) {
|
||||
addVertex(val);
|
||||
}
|
||||
// Add edge
|
||||
// Note that the edges elements represent vertex indices, i.e., corresponding to the vertices element indices
|
||||
for (List<int> e in edges) {
|
||||
addEdge(e[0], e[1]);
|
||||
}
|
||||
}
|
||||
|
||||
/* Get the number of vertices */
|
||||
int size() {
|
||||
return vertices.length;
|
||||
}
|
||||
|
||||
/* Add vertex */
|
||||
void addVertex(int val) {
|
||||
int n = size();
|
||||
// Add the value of the new vertex to the vertex list
|
||||
vertices.add(val);
|
||||
// Add a row to the adjacency matrix
|
||||
List<int> newRow = List.filled(n, 0, growable: true);
|
||||
adjMat.add(newRow);
|
||||
// Add a column to the adjacency matrix
|
||||
for (List<int> row in adjMat) {
|
||||
row.add(0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Remove vertex */
|
||||
void removeVertex(int index) {
|
||||
if (index >= size()) {
|
||||
throw IndexError;
|
||||
}
|
||||
// Remove the vertex at index from the vertex list
|
||||
vertices.removeAt(index);
|
||||
// Remove the row at index from the adjacency matrix
|
||||
adjMat.removeAt(index);
|
||||
// Remove the column at index from the adjacency matrix
|
||||
for (List<int> row in adjMat) {
|
||||
row.removeAt(index);
|
||||
}
|
||||
}
|
||||
|
||||
/* Add edge */
|
||||
// Parameters i, j correspond to the vertices element indices
|
||||
void addEdge(int i, int j) {
|
||||
// Handle index out of bounds and equality
|
||||
if (i < 0 || j < 0 || i >= size() || j >= size() || i == j) {
|
||||
throw IndexError;
|
||||
}
|
||||
// In an undirected graph, the adjacency matrix is symmetric about the main diagonal, i.e., (i, j) == (j, i)
|
||||
adjMat[i][j] = 1;
|
||||
adjMat[j][i] = 1;
|
||||
}
|
||||
|
||||
/* Remove edge */
|
||||
// Parameters i, j correspond to the vertices element indices
|
||||
void removeEdge(int i, int j) {
|
||||
// Handle index out of bounds and equality
|
||||
if (i < 0 || j < 0 || i >= size() || j >= size() || i == j) {
|
||||
throw IndexError;
|
||||
}
|
||||
adjMat[i][j] = 0;
|
||||
adjMat[j][i] = 0;
|
||||
}
|
||||
|
||||
/* Print adjacency matrix */
|
||||
void printAdjMat() {
|
||||
print("Vertex list = $vertices");
|
||||
print("Adjacency matrix = ");
|
||||
printMatrix(adjMat);
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
/* Add edge */
|
||||
// Note that the edges elements represent vertex indices, i.e., corresponding to the vertices element indices
|
||||
List<int> vertices = [1, 3, 2, 5, 4];
|
||||
List<List<int>> edges = [
|
||||
[0, 1],
|
||||
[0, 3],
|
||||
[1, 2],
|
||||
[2, 3],
|
||||
[2, 4],
|
||||
[3, 4],
|
||||
];
|
||||
GraphAdjMat graph = GraphAdjMat(vertices, edges);
|
||||
print("\nAfter initialization, graph is");
|
||||
graph.printAdjMat();
|
||||
|
||||
/* Add edge */
|
||||
// Add vertex
|
||||
graph.addEdge(0, 2);
|
||||
print("\nAfter adding edge 1-2, graph is");
|
||||
graph.printAdjMat();
|
||||
|
||||
/* Remove edge */
|
||||
// Vertices 1, 3 have indices 0, 1 respectively
|
||||
graph.removeEdge(0, 1);
|
||||
print("\nAfter removing edge 1-3, graph is");
|
||||
graph.printAdjMat();
|
||||
|
||||
/* Add vertex */
|
||||
graph.addVertex(6);
|
||||
print("\nAfter adding vertex 6, graph is");
|
||||
graph.printAdjMat();
|
||||
|
||||
/* Remove vertex */
|
||||
// Vertex 3 has index 1
|
||||
graph.removeVertex(1);
|
||||
print("\nAfter removing vertex 3, graph is");
|
||||
graph.printAdjMat();
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* File: graph_bfs.dart
|
||||
* Created Time: 2023-05-15
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import 'dart:collection';
|
||||
|
||||
import '../utils/vertex.dart';
|
||||
import 'graph_adjacency_list.dart';
|
||||
|
||||
/* Breadth-first traversal */
|
||||
List<Vertex> graphBFS(GraphAdjList graph, Vertex startVet) {
|
||||
// Use adjacency list to represent the graph, in order to obtain all adjacent vertices of a specified vertex
|
||||
// Vertex traversal sequence
|
||||
List<Vertex> res = [];
|
||||
// Hash set for recording vertices that have been visited
|
||||
Set<Vertex> visited = {};
|
||||
visited.add(startVet);
|
||||
// Queue used to implement BFS
|
||||
Queue<Vertex> que = Queue();
|
||||
que.add(startVet);
|
||||
// Starting from vertex vet, loop until all vertices are visited
|
||||
while (que.isNotEmpty) {
|
||||
Vertex vet = que.removeFirst(); // Dequeue the front vertex
|
||||
res.add(vet); // Record visited vertex
|
||||
// Traverse all adjacent vertices of this vertex
|
||||
for (Vertex adjVet in graph.adjList[vet]!) {
|
||||
if (visited.contains(adjVet)) {
|
||||
continue; // Skip vertices that have been visited
|
||||
}
|
||||
que.add(adjVet); // Only enqueue unvisited vertices
|
||||
visited.add(adjVet); // Mark this vertex as visited
|
||||
}
|
||||
}
|
||||
// Return vertex traversal sequence
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Dirver Code */
|
||||
void main() {
|
||||
/* Add edge */
|
||||
List<Vertex> v = Vertex.valsToVets([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
|
||||
List<List<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 = GraphAdjList(edges);
|
||||
print("\nAfter initialization, graph is");
|
||||
graph.printAdjList();
|
||||
|
||||
/* Breadth-first traversal */
|
||||
List<Vertex> res = graphBFS(graph, v[0]);
|
||||
print("\nBreadth-first traversal (BFS) vertex sequence is");
|
||||
print(Vertex.vetsToVals(res));
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* File: graph_dfs.dart
|
||||
* Created Time: 2023-05-15
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import '../utils/vertex.dart';
|
||||
import 'graph_adjacency_list.dart';
|
||||
|
||||
/* Depth-first traversal helper function */
|
||||
void dfs(
|
||||
GraphAdjList graph,
|
||||
Set<Vertex> visited,
|
||||
List<Vertex> res,
|
||||
Vertex vet,
|
||||
) {
|
||||
res.add(vet); // Record visited vertex
|
||||
visited.add(vet); // Mark this vertex as visited
|
||||
// Traverse all adjacent vertices of this vertex
|
||||
for (Vertex adjVet in graph.adjList[vet]!) {
|
||||
if (visited.contains(adjVet)) {
|
||||
continue; // Skip vertices that have been visited
|
||||
}
|
||||
// Recursively visit adjacent vertices
|
||||
dfs(graph, visited, res, adjVet);
|
||||
}
|
||||
}
|
||||
|
||||
/* Depth-first traversal */
|
||||
List<Vertex> graphDFS(GraphAdjList graph, Vertex startVet) {
|
||||
// Vertex traversal sequence
|
||||
List<Vertex> res = [];
|
||||
// Hash set for recording vertices that have been visited
|
||||
Set<Vertex> visited = {};
|
||||
dfs(graph, visited, res, startVet);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
/* Add edge */
|
||||
List<Vertex> v = Vertex.valsToVets([0, 1, 2, 3, 4, 5, 6]);
|
||||
List<List<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 = GraphAdjList(edges);
|
||||
print("\nAfter initialization, graph is");
|
||||
graph.printAdjList();
|
||||
|
||||
/* Depth-first traversal */
|
||||
List<Vertex> res = graphDFS(graph, v[0]);
|
||||
print("\nDepth-first traversal (DFS) vertex sequence is");
|
||||
print(Vertex.vetsToVals(res));
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* File: coin_change_greedy.dart
|
||||
* Created Time: 2023-08-11
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Coin change: Greedy algorithm */
|
||||
int coinChangeGreedy(List<int> coins, int amt) {
|
||||
// Assume coins list is sorted
|
||||
int i = coins.length - 1;
|
||||
int count = 0;
|
||||
// Loop to make greedy choices until no remaining amount
|
||||
while (amt > 0) {
|
||||
// Find the coin that is less than and closest to the remaining amount
|
||||
while (i > 0 && coins[i] > amt) {
|
||||
i--;
|
||||
}
|
||||
// Choose coins[i]
|
||||
amt -= coins[i];
|
||||
count++;
|
||||
}
|
||||
// If no feasible solution is found, return -1
|
||||
return amt == 0 ? count : -1;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
// Greedy algorithm: Can guarantee finding the global optimal solution
|
||||
List<int> coins = [1, 5, 10, 20, 50, 100];
|
||||
int amt = 186;
|
||||
int res = coinChangeGreedy(coins, amt);
|
||||
print("\ncoins = $coins, amt = $amt");
|
||||
print("Minimum coins needed to make $amt is $res");
|
||||
|
||||
// Greedy algorithm: Cannot guarantee finding the global optimal solution
|
||||
coins = [1, 20, 50];
|
||||
amt = 60;
|
||||
res = coinChangeGreedy(coins, amt);
|
||||
print("\ncoins = $coins, amt = $amt");
|
||||
print("Minimum coins needed to make $amt is $res");
|
||||
print("Actually the minimum number needed is 3, i.e., 20 + 20 + 20");
|
||||
|
||||
// Greedy algorithm: Cannot guarantee finding the global optimal solution
|
||||
coins = [1, 49, 50];
|
||||
amt = 98;
|
||||
res = coinChangeGreedy(coins, amt);
|
||||
print("\ncoins = $coins, amt = $amt");
|
||||
print("Minimum coins needed to make $amt is $res");
|
||||
print("Actually the minimum number needed is 2, i.e., 49 + 49");
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* File: fractional_knapsack.dart
|
||||
* Created Time: 2023-08-11
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Item */
|
||||
class Item {
|
||||
int w; // Item weight
|
||||
int v; // Item value
|
||||
|
||||
Item(this.w, this.v);
|
||||
}
|
||||
|
||||
/* Fractional knapsack: Greedy algorithm */
|
||||
double fractionalKnapsack(List<int> wgt, List<int> val, int cap) {
|
||||
// Create item list with two attributes: weight, value
|
||||
List<Item> items = List.generate(wgt.length, (i) => Item(wgt[i], val[i]));
|
||||
// Sort by unit value item.v / item.w from high to low
|
||||
items.sort((a, b) => (b.v / b.w).compareTo(a.v / a.w));
|
||||
// Loop for greedy selection
|
||||
double res = 0;
|
||||
for (Item item in items) {
|
||||
if (item.w <= cap) {
|
||||
// If remaining capacity is sufficient, put the entire current item into the knapsack
|
||||
res += item.v;
|
||||
cap -= item.w;
|
||||
} else {
|
||||
// If remaining capacity is insufficient, put part of the current item into the knapsack
|
||||
res += item.v / item.w * cap;
|
||||
// No remaining capacity, so break out of the loop
|
||||
break;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
List<int> wgt = [10, 20, 30, 40, 50];
|
||||
List<int> val = [50, 120, 150, 210, 240];
|
||||
int cap = 50;
|
||||
|
||||
// Greedy algorithm
|
||||
double res = fractionalKnapsack(wgt, val, cap);
|
||||
print("Maximum item value not exceeding knapsack capacity is $res");
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* File: max_capacity.dart
|
||||
* Created Time: 2023-08-11
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
/* Max capacity: Greedy algorithm */
|
||||
int maxCapacity(List<int> ht) {
|
||||
// Initialize i, j to be at both ends of the array
|
||||
int i = 0, j = ht.length - 1;
|
||||
// Initial max capacity is 0
|
||||
int res = 0;
|
||||
// Loop for greedy selection until the two boards meet
|
||||
while (i < j) {
|
||||
// Update max capacity
|
||||
int cap = min(ht[i], ht[j]) * (j - i);
|
||||
res = max(res, cap);
|
||||
// Move the shorter board inward
|
||||
if (ht[i] < ht[j]) {
|
||||
i++;
|
||||
} else {
|
||||
j--;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
List<int> ht = [3, 8, 5, 2, 7, 7, 3, 4];
|
||||
|
||||
// Greedy algorithm
|
||||
int res = maxCapacity(ht);
|
||||
print("Maximum capacity is $res");
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* File: max_product_cutting.dart
|
||||
* Created Time: 2023-08-11
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
/* Max product cutting: Greedy algorithm */
|
||||
int maxProductCutting(int n) {
|
||||
// When n <= 3, must cut out a 1
|
||||
if (n <= 3) {
|
||||
return 1 * (n - 1);
|
||||
}
|
||||
// Greedily cut out 3, a is the number of 3s, b is the remainder
|
||||
int a = n ~/ 3;
|
||||
int b = n % 3;
|
||||
if (b == 1) {
|
||||
// When the remainder is 1, convert a pair of 1 * 3 to 2 * 2
|
||||
return (pow(3, a - 1) * 2 * 2).toInt();
|
||||
}
|
||||
if (b == 2) {
|
||||
// When the remainder is 2, do nothing
|
||||
return (pow(3, a) * 2).toInt();
|
||||
}
|
||||
// When the remainder is 0, do nothing
|
||||
return pow(3, a).toInt();
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
int n = 58;
|
||||
|
||||
// Greedy algorithm
|
||||
int res = maxProductCutting(n);
|
||||
print("Maximum cutting product is $res");
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* File: array_hash_map.dart
|
||||
* Created Time: 2023-03-29
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Key-value pair */
|
||||
class Pair {
|
||||
int key;
|
||||
String val;
|
||||
Pair(this.key, this.val);
|
||||
}
|
||||
|
||||
/* Hash table based on array implementation */
|
||||
class ArrayHashMap {
|
||||
late List<Pair?> _buckets;
|
||||
|
||||
ArrayHashMap() {
|
||||
// Initialize array with 100 buckets
|
||||
_buckets = List.filled(100, null);
|
||||
}
|
||||
|
||||
/* Hash function */
|
||||
int _hashFunc(int key) {
|
||||
final int index = key % 100;
|
||||
return index;
|
||||
}
|
||||
|
||||
/* Query operation */
|
||||
String? get(int key) {
|
||||
final int index = _hashFunc(key);
|
||||
final Pair? pair = _buckets[index];
|
||||
if (pair == null) {
|
||||
return null;
|
||||
}
|
||||
return pair.val;
|
||||
}
|
||||
|
||||
/* Add operation */
|
||||
void put(int key, String val) {
|
||||
final Pair pair = Pair(key, val);
|
||||
final int index = _hashFunc(key);
|
||||
_buckets[index] = pair;
|
||||
}
|
||||
|
||||
/* Remove operation */
|
||||
void remove(int key) {
|
||||
final int index = _hashFunc(key);
|
||||
_buckets[index] = null;
|
||||
}
|
||||
|
||||
/* Get all key-value pairs */
|
||||
List<Pair> pairSet() {
|
||||
List<Pair> pairSet = [];
|
||||
for (final Pair? pair in _buckets) {
|
||||
if (pair != null) {
|
||||
pairSet.add(pair);
|
||||
}
|
||||
}
|
||||
return pairSet;
|
||||
}
|
||||
|
||||
/* Get all keys */
|
||||
List<int> keySet() {
|
||||
List<int> keySet = [];
|
||||
for (final Pair? pair in _buckets) {
|
||||
if (pair != null) {
|
||||
keySet.add(pair.key);
|
||||
}
|
||||
}
|
||||
return keySet;
|
||||
}
|
||||
|
||||
/* Get all values */
|
||||
List<String> values() {
|
||||
List<String> valueSet = [];
|
||||
for (final Pair? pair in _buckets) {
|
||||
if (pair != null) {
|
||||
valueSet.add(pair.val);
|
||||
}
|
||||
}
|
||||
return valueSet;
|
||||
}
|
||||
|
||||
/* Print hash table */
|
||||
void printHashMap() {
|
||||
for (final Pair kv in pairSet()) {
|
||||
print("${kv.key} -> ${kv.val}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
/* Initialize hash table */
|
||||
final 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");
|
||||
print("\nAfter adding is complete, hash table is\nKey -> Value");
|
||||
map.printHashMap();
|
||||
|
||||
/* Query operation */
|
||||
// Input key into hash table to get value
|
||||
String? name = map.get(15937);
|
||||
print("\nInput student ID 15937, found name $name");
|
||||
|
||||
/* Remove operation */
|
||||
// Remove key-value pair (key, value) from hash table
|
||||
map.remove(10583);
|
||||
print("\nAfter removing 10583, hash table is\nKey -> Value");
|
||||
map.printHashMap();
|
||||
|
||||
/* Traverse hash table */
|
||||
print("\nTraverse key-value pairs Key->Value");
|
||||
map.pairSet().forEach((kv) => print("${kv.key} -> ${kv.val}"));
|
||||
print("\nTraverse keys only Key");
|
||||
map.keySet().forEach((key) => print("$key"));
|
||||
print("\nTraverse values only Value");
|
||||
map.values().forEach((val) => print("$val"));
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* File: built_in_hash.dart
|
||||
* Created Time: 2023-06-25
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import '../chapter_stack_and_queue/linkedlist_deque.dart';
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
int _num = 3;
|
||||
int hashNum = _num.hashCode;
|
||||
print("Hash value of integer $_num is $hashNum");
|
||||
|
||||
bool bol = true;
|
||||
int hashBol = bol.hashCode;
|
||||
print("Hash value of boolean $bol is $hashBol");
|
||||
|
||||
double dec = 3.14159;
|
||||
int hashDec = dec.hashCode;
|
||||
print("Hash value of decimal $dec is $hashDec");
|
||||
|
||||
String str = "Hello Algo";
|
||||
int hashStr = str.hashCode;
|
||||
print("Hash value of string $str is $hashStr");
|
||||
|
||||
List arr = [12836, "Xiao Ha"];
|
||||
int hashArr = arr.hashCode;
|
||||
print("Hash value of array $arr is $hashArr");
|
||||
|
||||
ListNode obj = new ListNode(0);
|
||||
int hashObj = obj.hashCode;
|
||||
print("Hash value of node object $obj is $hashObj");
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* File: hash_map.dart
|
||||
* Created Time: 2023-03-29
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
/* Initialize hash table */
|
||||
final 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";
|
||||
print("\nAfter adding is complete, hash table is\nKey -> Value");
|
||||
map.forEach((key, value) => print("$key -> $value"));
|
||||
|
||||
/* Query operation */
|
||||
// Input key into hash table to get value
|
||||
final String? name = map[15937];
|
||||
print("\nInput student ID 15937, found name $name");
|
||||
|
||||
/* Remove operation */
|
||||
// Remove key-value pair (key, value) from hash table
|
||||
map.remove(10583);
|
||||
print("\nAfter removing 10583, hash table is\nKey -> Value");
|
||||
map.forEach((key, value) => print("$key -> $value"));
|
||||
|
||||
/* Traverse hash table */
|
||||
print("\nTraverse key-value pairs Key->Value");
|
||||
map.forEach((key, value) => print("$key -> $value"));
|
||||
print("\nTraverse keys only Key");
|
||||
map.keys.forEach((key) => print(key));
|
||||
print("\nTraverse values only Value");
|
||||
map.forEach((key, value) => print("$value"));
|
||||
map.values.forEach((value) => print(value));
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* File: hash_map_chaining.dart
|
||||
* Created Time: 2023-06-24
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import 'array_hash_map.dart';
|
||||
|
||||
/* Hash table with separate chaining */
|
||||
class HashMapChaining {
|
||||
late int size; // Number of key-value pairs
|
||||
late int capacity; // Hash table capacity
|
||||
late double loadThres; // Load factor threshold for triggering expansion
|
||||
late int extendRatio; // Expansion multiplier
|
||||
late List<List<Pair>> buckets; // Bucket array
|
||||
|
||||
/* Constructor */
|
||||
HashMapChaining() {
|
||||
size = 0;
|
||||
capacity = 4;
|
||||
loadThres = 2.0 / 3.0;
|
||||
extendRatio = 2;
|
||||
buckets = List.generate(capacity, (_) => []);
|
||||
}
|
||||
|
||||
/* Hash function */
|
||||
int hashFunc(int key) {
|
||||
return key % capacity;
|
||||
}
|
||||
|
||||
/* Load factor */
|
||||
double loadFactor() {
|
||||
return size / capacity;
|
||||
}
|
||||
|
||||
/* Query operation */
|
||||
String? get(int key) {
|
||||
int index = hashFunc(key);
|
||||
List<Pair> bucket = buckets[index];
|
||||
// Traverse bucket, if key is found, return corresponding val
|
||||
for (Pair pair in bucket) {
|
||||
if (pair.key == key) {
|
||||
return pair.val;
|
||||
}
|
||||
}
|
||||
// If key is not found, return null
|
||||
return null;
|
||||
}
|
||||
|
||||
/* Add operation */
|
||||
void put(int key, String val) {
|
||||
// When load factor exceeds threshold, perform expansion
|
||||
if (loadFactor() > loadThres) {
|
||||
extend();
|
||||
}
|
||||
int index = hashFunc(key);
|
||||
List<Pair> bucket = buckets[index];
|
||||
// Traverse bucket, if specified key is encountered, update corresponding val and return
|
||||
for (Pair pair in bucket) {
|
||||
if (pair.key == key) {
|
||||
pair.val = val;
|
||||
return;
|
||||
}
|
||||
}
|
||||
// If key does not exist, append key-value pair to the end
|
||||
Pair pair = Pair(key, val);
|
||||
bucket.add(pair);
|
||||
size++;
|
||||
}
|
||||
|
||||
/* Remove operation */
|
||||
void remove(int key) {
|
||||
int index = hashFunc(key);
|
||||
List<Pair> bucket = buckets[index];
|
||||
// Traverse bucket and remove key-value pair from it
|
||||
for (Pair pair in bucket) {
|
||||
if (pair.key == key) {
|
||||
bucket.remove(pair);
|
||||
size--;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Expand hash table */
|
||||
void extend() {
|
||||
// Temporarily store the original hash table
|
||||
List<List<Pair>> bucketsTmp = buckets;
|
||||
// Initialize expanded new hash table
|
||||
capacity *= extendRatio;
|
||||
buckets = List.generate(capacity, (_) => []);
|
||||
size = 0;
|
||||
// Move key-value pairs from original hash table to new hash table
|
||||
for (List<Pair> bucket in bucketsTmp) {
|
||||
for (Pair pair in bucket) {
|
||||
put(pair.key, pair.val);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Print hash table */
|
||||
void printHashMap() {
|
||||
for (List<Pair> bucket in buckets) {
|
||||
List<String> res = [];
|
||||
for (Pair pair in bucket) {
|
||||
res.add("${pair.key} -> ${pair.val}");
|
||||
}
|
||||
print(res);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
/* Initialize 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");
|
||||
print("\nAfter adding is complete, hash table is\nKey -> Value");
|
||||
map.printHashMap();
|
||||
|
||||
/* Query operation */
|
||||
// Input key into hash table to get value
|
||||
String? name = map.get(13276);
|
||||
print("\nInput student ID 13276, found name ${name}");
|
||||
|
||||
/* Remove operation */
|
||||
// Remove key-value pair (key, value) from hash table
|
||||
map.remove(12836);
|
||||
print("\nAfter removing 12836, hash table is\nKey -> Value");
|
||||
map.printHashMap();
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
/**
|
||||
* File: hash_map_open_addressing.dart
|
||||
* Created Time: 2023-06-25
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import 'array_hash_map.dart';
|
||||
|
||||
/* Hash table with open addressing */
|
||||
class HashMapOpenAddressing {
|
||||
late int _size; // Number of key-value pairs
|
||||
int _capacity = 4; // Hash table capacity
|
||||
double _loadThres = 2.0 / 3.0; // Load factor threshold for triggering expansion
|
||||
int _extendRatio = 2; // Expansion multiplier
|
||||
late List<Pair?> _buckets; // Bucket array
|
||||
Pair _TOMBSTONE = Pair(-1, "-1"); // Removal marker
|
||||
|
||||
/* Constructor */
|
||||
HashMapOpenAddressing() {
|
||||
_size = 0;
|
||||
_buckets = List.generate(_capacity, (index) => null);
|
||||
}
|
||||
|
||||
/* Hash function */
|
||||
int hashFunc(int key) {
|
||||
return key % _capacity;
|
||||
}
|
||||
|
||||
/* Load factor */
|
||||
double loadFactor() {
|
||||
return _size / _capacity;
|
||||
}
|
||||
|
||||
/* Search for bucket index corresponding to key */
|
||||
int findBucket(int key) {
|
||||
int index = hashFunc(key);
|
||||
int firstTombstone = -1;
|
||||
// Linear probing, break when encountering an empty bucket
|
||||
while (_buckets[index] != null) {
|
||||
// If key is encountered, return the corresponding bucket index
|
||||
if (_buckets[index]!.key == key) {
|
||||
// If a removal marker was encountered before, move the key-value pair to that index
|
||||
if (firstTombstone != -1) {
|
||||
_buckets[firstTombstone] = _buckets[index];
|
||||
_buckets[index] = _TOMBSTONE;
|
||||
return firstTombstone; // Return the moved bucket index
|
||||
}
|
||||
return index; // Return bucket index
|
||||
}
|
||||
// Record the first removal marker encountered
|
||||
if (firstTombstone == -1 && _buckets[index] == _TOMBSTONE) {
|
||||
firstTombstone = index;
|
||||
}
|
||||
// Calculate bucket index, wrap around to the head if past the tail
|
||||
index = (index + 1) % _capacity;
|
||||
}
|
||||
// If key does not exist, return the index for insertion
|
||||
return firstTombstone == -1 ? index : firstTombstone;
|
||||
}
|
||||
|
||||
/* Query operation */
|
||||
String? get(int key) {
|
||||
// Search for bucket index corresponding to key
|
||||
int index = findBucket(key);
|
||||
// If key-value pair is found, return corresponding val
|
||||
if (_buckets[index] != null && _buckets[index] != _TOMBSTONE) {
|
||||
return _buckets[index]!.val;
|
||||
}
|
||||
// If key-value pair does not exist, return null
|
||||
return null;
|
||||
}
|
||||
|
||||
/* Add operation */
|
||||
void put(int key, String val) {
|
||||
// When load factor exceeds threshold, perform expansion
|
||||
if (loadFactor() > _loadThres) {
|
||||
extend();
|
||||
}
|
||||
// Search for bucket index corresponding to key
|
||||
int index = findBucket(key);
|
||||
// If key-value pair is found, overwrite val and return
|
||||
if (_buckets[index] != null && _buckets[index] != _TOMBSTONE) {
|
||||
_buckets[index]!.val = val;
|
||||
return;
|
||||
}
|
||||
// If key-value pair does not exist, add the key-value pair
|
||||
_buckets[index] = new Pair(key, val);
|
||||
_size++;
|
||||
}
|
||||
|
||||
/* Remove operation */
|
||||
void remove(int key) {
|
||||
// Search for bucket index corresponding to key
|
||||
int index = findBucket(key);
|
||||
// If key-value pair is found, overwrite it with removal marker
|
||||
if (_buckets[index] != null && _buckets[index] != _TOMBSTONE) {
|
||||
_buckets[index] = _TOMBSTONE;
|
||||
_size--;
|
||||
}
|
||||
}
|
||||
|
||||
/* Expand hash table */
|
||||
void extend() {
|
||||
// Temporarily store the original hash table
|
||||
List<Pair?> bucketsTmp = _buckets;
|
||||
// Initialize expanded new hash table
|
||||
_capacity *= _extendRatio;
|
||||
_buckets = List.generate(_capacity, (index) => null);
|
||||
_size = 0;
|
||||
// Move key-value pairs from original hash table to new hash table
|
||||
for (Pair? pair in bucketsTmp) {
|
||||
if (pair != null && pair != _TOMBSTONE) {
|
||||
put(pair.key, pair.val);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Print hash table */
|
||||
void printHashMap() {
|
||||
for (Pair? pair in _buckets) {
|
||||
if (pair == null) {
|
||||
print("null");
|
||||
} else if (pair == _TOMBSTONE) {
|
||||
print("TOMBSTONE");
|
||||
} else {
|
||||
print("${pair.key} -> ${pair.val}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
/* Initialize hash table */
|
||||
HashMapOpenAddressing map = HashMapOpenAddressing();
|
||||
|
||||
/* 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");
|
||||
print("\nAfter adding is complete, hash table is\nKey -> Value");
|
||||
map.printHashMap();
|
||||
|
||||
/* Query operation */
|
||||
// Input key into hash table to get value
|
||||
String? name = map.get(13276);
|
||||
print("\nInput student ID 13276, found name $name");
|
||||
|
||||
/* Remove operation */
|
||||
// Remove key-value pair (key, value) from hash table
|
||||
map.remove(16750);
|
||||
print("\nAfter removing 16750, hash table is\nKey -> Value");
|
||||
map.printHashMap();
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* File: simple_hash.dart
|
||||
* Created Time: 2023-06-25
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Additive hash */
|
||||
int addHash(String key) {
|
||||
int hash = 0;
|
||||
final int MODULUS = 1000000007;
|
||||
for (int i = 0; i < key.length; i++) {
|
||||
hash = (hash + key.codeUnitAt(i)) % MODULUS;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
/* Multiplicative hash */
|
||||
int mulHash(String key) {
|
||||
int hash = 0;
|
||||
final int MODULUS = 1000000007;
|
||||
for (int i = 0; i < key.length; i++) {
|
||||
hash = (31 * hash + key.codeUnitAt(i)) % MODULUS;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
/* XOR hash */
|
||||
int xorHash(String key) {
|
||||
int hash = 0;
|
||||
final int MODULUS = 1000000007;
|
||||
for (int i = 0; i < key.length; i++) {
|
||||
hash ^= key.codeUnitAt(i);
|
||||
}
|
||||
return hash & MODULUS;
|
||||
}
|
||||
|
||||
/* Rotational hash */
|
||||
int rotHash(String key) {
|
||||
int hash = 0;
|
||||
final int MODULUS = 1000000007;
|
||||
for (int i = 0; i < key.length; i++) {
|
||||
hash = ((hash << 4) ^ (hash >> 28) ^ key.codeUnitAt(i)) % MODULUS;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
/* Dirver Code */
|
||||
void main() {
|
||||
String key = "Hello Algo";
|
||||
|
||||
int hash = addHash(key);
|
||||
print("Additive hash value is $hash");
|
||||
|
||||
hash = mulHash(key);
|
||||
print("Multiplicative hash value is $hash");
|
||||
|
||||
hash = xorHash(key);
|
||||
print("XOR hash value is $hash");
|
||||
|
||||
hash = rotHash(key);
|
||||
print("Rotational hash value is $hash");
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* File: my_heap.dart
|
||||
* Created Time: 2023-04-09
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import '../utils/print_util.dart';
|
||||
|
||||
/* Max heap */
|
||||
class MaxHeap {
|
||||
late List<int> _maxHeap;
|
||||
|
||||
/* Constructor, build heap based on input list */
|
||||
MaxHeap(List<int> nums) {
|
||||
// Add list elements to heap as is
|
||||
_maxHeap = nums;
|
||||
// Heapify all nodes except leaf nodes
|
||||
for (int i = _parent(size() - 1); i >= 0; i--) {
|
||||
siftDown(i);
|
||||
}
|
||||
}
|
||||
|
||||
/* Get index of left child node */
|
||||
int _left(int i) {
|
||||
return 2 * i + 1;
|
||||
}
|
||||
|
||||
/* Get index of right child node */
|
||||
int _right(int i) {
|
||||
return 2 * i + 2;
|
||||
}
|
||||
|
||||
/* Get index of parent node */
|
||||
int _parent(int i) {
|
||||
return (i - 1) ~/ 2; // Floor division
|
||||
}
|
||||
|
||||
/* Swap elements */
|
||||
void _swap(int i, int j) {
|
||||
int tmp = _maxHeap[i];
|
||||
_maxHeap[i] = _maxHeap[j];
|
||||
_maxHeap[j] = tmp;
|
||||
}
|
||||
|
||||
/* Get heap size */
|
||||
int size() {
|
||||
return _maxHeap.length;
|
||||
}
|
||||
|
||||
/* Check if heap is empty */
|
||||
bool isEmpty() {
|
||||
return size() == 0;
|
||||
}
|
||||
|
||||
/* Access top element */
|
||||
int peek() {
|
||||
return _maxHeap[0];
|
||||
}
|
||||
|
||||
/* Element enters heap */
|
||||
void push(int val) {
|
||||
// Add node
|
||||
_maxHeap.add(val);
|
||||
// Heapify from bottom to top
|
||||
siftUp(size() - 1);
|
||||
}
|
||||
|
||||
/* Starting from node i, heapify from bottom to top */
|
||||
void siftUp(int i) {
|
||||
while (true) {
|
||||
// Get parent node of node i
|
||||
int p = _parent(i);
|
||||
// When "crossing root node" or "node needs no repair", end heapify
|
||||
if (p < 0 || _maxHeap[i] <= _maxHeap[p]) {
|
||||
break;
|
||||
}
|
||||
// Swap two nodes
|
||||
_swap(i, p);
|
||||
// Loop upward heapify
|
||||
i = p;
|
||||
}
|
||||
}
|
||||
|
||||
/* Element exits heap */
|
||||
int pop() {
|
||||
// Handle empty case
|
||||
if (isEmpty()) throw Exception('Heap is empty');
|
||||
// Delete node
|
||||
_swap(0, size() - 1);
|
||||
// Remove node
|
||||
int val = _maxHeap.removeLast();
|
||||
// Return top element
|
||||
siftDown(0);
|
||||
// Return heap top element
|
||||
return val;
|
||||
}
|
||||
|
||||
/* Starting from node i, heapify from top to bottom */
|
||||
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
|
||||
int l = _left(i);
|
||||
int r = _right(i);
|
||||
int ma = i;
|
||||
if (l < size() && _maxHeap[l] > _maxHeap[ma]) ma = l;
|
||||
if (r < size() && _maxHeap[r] > _maxHeap[ma]) ma = r;
|
||||
// Swap two nodes
|
||||
if (ma == i) break;
|
||||
// Swap two nodes
|
||||
_swap(i, ma);
|
||||
// Loop downwards heapification
|
||||
i = ma;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void print() {
|
||||
printHeap(_maxHeap);
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
/* Consider negating the elements before entering the heap, which can reverse the size relationship, thus implementing max heap */
|
||||
MaxHeap maxHeap = MaxHeap([9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2]);
|
||||
print("\nAfter inputting list and building heap");
|
||||
maxHeap.print();
|
||||
|
||||
/* Check if heap is empty */
|
||||
int peek = maxHeap.peek();
|
||||
print("\nHeap top element is $peek");
|
||||
|
||||
/* Element enters heap */
|
||||
int val = 7;
|
||||
maxHeap.push(val);
|
||||
print("\nAfter element $val pushes to heap");
|
||||
maxHeap.print();
|
||||
|
||||
/* Time complexity is O(n), not O(nlogn) */
|
||||
peek = maxHeap.pop();
|
||||
print("\nAfter heap top element $peek pops from heap");
|
||||
maxHeap.print();
|
||||
|
||||
/* Get heap size */
|
||||
int size = maxHeap.size();
|
||||
print("\nHeap size is $size");
|
||||
|
||||
/* Check if heap is empty */
|
||||
bool isEmpty = maxHeap.isEmpty();
|
||||
print("\nIs heap empty $isEmpty");
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
/**
|
||||
* File: top_k.dart
|
||||
* Created Time: 2023-08-15
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import '../utils/print_util.dart';
|
||||
|
||||
/* Find the largest k elements in array based on heap */
|
||||
MinHeap topKHeap(List<int> nums, int k) {
|
||||
// Initialize min heap, push first k elements of array to heap
|
||||
MinHeap heap = MinHeap(nums.sublist(0, k));
|
||||
// Starting from the (k+1)th element, maintain heap length as k
|
||||
for (int i = k; i < nums.length; i++) {
|
||||
// If current element is greater than top element, top element exits heap, current element enters heap
|
||||
if (nums[i] > heap.peek()) {
|
||||
heap.pop();
|
||||
heap.push(nums[i]);
|
||||
}
|
||||
}
|
||||
return heap;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
List<int> nums = [1, 7, 6, 3, 2];
|
||||
int k = 3;
|
||||
|
||||
MinHeap res = topKHeap(nums, k);
|
||||
print("The largest $k elements are");
|
||||
res.print();
|
||||
}
|
||||
|
||||
/* Min heap */
|
||||
class MinHeap {
|
||||
late List<int> _minHeap;
|
||||
|
||||
/* Constructor, build heap based on input list */
|
||||
MinHeap(List<int> nums) {
|
||||
// Add list elements to heap as is
|
||||
_minHeap = nums;
|
||||
// Heapify all nodes except leaf nodes
|
||||
for (int i = _parent(size() - 1); i >= 0; i--) {
|
||||
siftDown(i);
|
||||
}
|
||||
}
|
||||
|
||||
/* Return elements in heap */
|
||||
List<int> getHeap() {
|
||||
return _minHeap;
|
||||
}
|
||||
|
||||
/* Get index of left child node */
|
||||
int _left(int i) {
|
||||
return 2 * i + 1;
|
||||
}
|
||||
|
||||
/* Get index of right child node */
|
||||
int _right(int i) {
|
||||
return 2 * i + 2;
|
||||
}
|
||||
|
||||
/* Get index of parent node */
|
||||
int _parent(int i) {
|
||||
return (i - 1) ~/ 2; // Floor division
|
||||
}
|
||||
|
||||
/* Swap elements */
|
||||
void _swap(int i, int j) {
|
||||
int tmp = _minHeap[i];
|
||||
_minHeap[i] = _minHeap[j];
|
||||
_minHeap[j] = tmp;
|
||||
}
|
||||
|
||||
/* Get heap size */
|
||||
int size() {
|
||||
return _minHeap.length;
|
||||
}
|
||||
|
||||
/* Check if heap is empty */
|
||||
bool isEmpty() {
|
||||
return size() == 0;
|
||||
}
|
||||
|
||||
/* Access top element */
|
||||
int peek() {
|
||||
return _minHeap[0];
|
||||
}
|
||||
|
||||
/* Element enters heap */
|
||||
void push(int val) {
|
||||
// Add node
|
||||
_minHeap.add(val);
|
||||
// Heapify from bottom to top
|
||||
siftUp(size() - 1);
|
||||
}
|
||||
|
||||
/* Starting from node i, heapify from bottom to top */
|
||||
void siftUp(int i) {
|
||||
while (true) {
|
||||
// Get parent node of node i
|
||||
int p = _parent(i);
|
||||
// When "crossing root node" or "node needs no repair", end heapify
|
||||
if (p < 0 || _minHeap[i] >= _minHeap[p]) {
|
||||
break;
|
||||
}
|
||||
// Swap two nodes
|
||||
_swap(i, p);
|
||||
// Loop upward heapify
|
||||
i = p;
|
||||
}
|
||||
}
|
||||
|
||||
/* Element exits heap */
|
||||
int pop() {
|
||||
// Handle empty case
|
||||
if (isEmpty()) throw Exception('Heap is empty');
|
||||
// Delete node
|
||||
_swap(0, size() - 1);
|
||||
// Remove node
|
||||
int val = _minHeap.removeLast();
|
||||
// Return top element
|
||||
siftDown(0);
|
||||
// Return heap top element
|
||||
return val;
|
||||
}
|
||||
|
||||
/* Starting from node i, heapify from top to bottom */
|
||||
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
|
||||
int l = _left(i);
|
||||
int r = _right(i);
|
||||
int mi = i;
|
||||
if (l < size() && _minHeap[l] < _minHeap[mi]) mi = l;
|
||||
if (r < size() && _minHeap[r] < _minHeap[mi]) mi = r;
|
||||
// Swap two nodes
|
||||
if (mi == i) break;
|
||||
// Swap two nodes
|
||||
_swap(i, mi);
|
||||
// Loop downwards heapification
|
||||
i = mi;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void print() {
|
||||
printHeap(_minHeap);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* File: binary_search.dart
|
||||
* Created Time: 2023-05-12
|
||||
* Author: Jefferson (JeffersonHuang77@gmail.com)
|
||||
*/
|
||||
|
||||
/* Binary search (closed interval on both sides) */
|
||||
int binarySearch(List<int> nums, int target) {
|
||||
// Initialize closed interval [0, n-1], i.e., i, j point to the first and last elements of the array
|
||||
int i = 0, j = nums.length - 1;
|
||||
// Loop, exit when the search interval is empty (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]
|
||||
i = m + 1;
|
||||
} else if (nums[m] > target) {
|
||||
// This means target is in the interval [i, m-1]
|
||||
j = m - 1;
|
||||
} else {
|
||||
// Found the target element, return its index
|
||||
return m;
|
||||
}
|
||||
}
|
||||
// Target element not found, return -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Binary search (left-closed right-open interval) */
|
||||
int binarySearchLCRO(List<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
|
||||
int i = 0, j = nums.length;
|
||||
// Loop, exit when the search interval is empty (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)
|
||||
i = m + 1;
|
||||
} else if (nums[m] > target) {
|
||||
// This means target is in the interval [i, m)
|
||||
j = m;
|
||||
} else {
|
||||
// Found the target element, return its index
|
||||
return m;
|
||||
}
|
||||
}
|
||||
// Target element not found, return -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Driver Code*/
|
||||
void main() {
|
||||
int target = 6;
|
||||
final nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35];
|
||||
|
||||
/* Binary search (closed interval) */
|
||||
int index = binarySearch(nums, target);
|
||||
print('Index of target element 6 = $index');
|
||||
|
||||
/* Binary search (left-closed right-open interval) */
|
||||
index = binarySearchLCRO(nums, target);
|
||||
print('Index of target element 6 = $index');
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* File: binary_search_edge.dart
|
||||
* Created Time: 2023-08-14
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import 'binary_search_insertion.dart';
|
||||
|
||||
/* Binary search for the leftmost target */
|
||||
int binarySearchLeftEdge(List<int> nums, int target) {
|
||||
// Equivalent to finding the insertion point of target
|
||||
int i = binarySearchInsertion(nums, target);
|
||||
// Target not found, return -1
|
||||
if (i == nums.length || nums[i] != target) {
|
||||
return -1;
|
||||
}
|
||||
// Found target, return index i
|
||||
return i;
|
||||
}
|
||||
|
||||
/* Binary search for the rightmost target */
|
||||
int binarySearchRightEdge(List<int> nums, int target) {
|
||||
// Convert to finding the leftmost target + 1
|
||||
int i = binarySearchInsertion(nums, target + 1);
|
||||
// j points to the rightmost target, i points to the first element greater than target
|
||||
int j = i - 1;
|
||||
// Target not found, return -1
|
||||
if (j == -1 || nums[j] != target) {
|
||||
return -1;
|
||||
}
|
||||
// Found target, return index j
|
||||
return j;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
// Array with duplicate elements
|
||||
List<int> nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15];
|
||||
print("\nArray nums = $nums");
|
||||
|
||||
// Binary search left and right boundaries
|
||||
for (int target in [6, 7]) {
|
||||
int index = binarySearchLeftEdge(nums, target);
|
||||
print("Leftmost element $target index is $index");
|
||||
index = binarySearchRightEdge(nums, target);
|
||||
print("Rightmost element $target index is $index");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* File: binary_search_insertion.dart
|
||||
* Created Time: 2023-08-14
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Binary search for insertion point (no duplicate elements) */
|
||||
int binarySearchInsertionSimple(List<int> nums, int target) {
|
||||
int i = 0, j = nums.length - 1; // Initialize 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]
|
||||
} else if (nums[m] > target) {
|
||||
j = m - 1; // target is in the interval [i, m-1]
|
||||
} else {
|
||||
return m; // Found target, return insertion point m
|
||||
}
|
||||
}
|
||||
// Target not found, return insertion point i
|
||||
return i;
|
||||
}
|
||||
|
||||
/* Binary search for insertion point (with duplicate elements) */
|
||||
int binarySearchInsertion(List<int> nums, int target) {
|
||||
int i = 0, j = nums.length - 1; // Initialize 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]
|
||||
} else if (nums[m] > target) {
|
||||
j = m - 1; // target is in the interval [i, m-1]
|
||||
} else {
|
||||
j = m - 1; // The first element less than target is in the interval [i, m-1]
|
||||
}
|
||||
}
|
||||
// Return insertion point i
|
||||
return i;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
// Array without duplicate elements
|
||||
List<int> nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35];
|
||||
print("\nArray nums = $nums");
|
||||
// Binary search for insertion point
|
||||
for (int target in [6, 9]) {
|
||||
int index = binarySearchInsertionSimple(nums, target);
|
||||
print("Insertion point index for element $target is $index");
|
||||
}
|
||||
|
||||
// Array with duplicate elements
|
||||
nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15];
|
||||
print("\nArray nums = $nums");
|
||||
// Binary search for insertion point
|
||||
for (int target in [2, 6, 20]) {
|
||||
int index = binarySearchInsertion(nums, target);
|
||||
print("Insertion point index for element $target is $index");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* File: hashing_search.dart
|
||||
* Created Time: 2023-05-12
|
||||
* Author: Jefferson (JeffersonHuang77@gmail.com)
|
||||
*/
|
||||
|
||||
import 'dart:collection';
|
||||
import '../utils/list_node.dart';
|
||||
|
||||
/* Hash search (array) */
|
||||
int hashingSearchArray(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
|
||||
if (!map.containsKey(target)) {
|
||||
return -1;
|
||||
}
|
||||
return map[target]!;
|
||||
}
|
||||
|
||||
/* Hash search (linked list) */
|
||||
ListNode? hashingSearchLinkedList(Map<int, ListNode> map, int target) {
|
||||
// Hash table key: target node value, value: node object
|
||||
// If key is not in hash table, return null
|
||||
if (!map.containsKey(target)) {
|
||||
return null;
|
||||
}
|
||||
return map[target]!;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
int target = 3;
|
||||
|
||||
/* Hash search (array) */
|
||||
List<int> nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8];
|
||||
// Initialize hash table
|
||||
Map<int, int> map = HashMap();
|
||||
for (int i = 0; i < nums.length; i++) {
|
||||
map.putIfAbsent(nums[i], () => i); // key: element, value: index
|
||||
}
|
||||
int index = hashingSearchArray(map, target);
|
||||
print('Index of target element 3 = $index');
|
||||
|
||||
/* Hash search (linked list) */
|
||||
ListNode? head = listToLinkedList(nums);
|
||||
// Initialize hash table
|
||||
Map<int, ListNode> map1 = HashMap();
|
||||
while (head != null) {
|
||||
map1.putIfAbsent(head.val, () => head!); // key: node value, value: node
|
||||
head = head.next;
|
||||
}
|
||||
ListNode? node = hashingSearchLinkedList(map1, target);
|
||||
print('Node object corresponding to target node value 3 is $node');
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* File: linear_search.dart
|
||||
* Created Time: 2023-05-12
|
||||
* Author: Jefferson (JeffersonHuang77@gmail.com)
|
||||
*/
|
||||
|
||||
import '../utils/list_node.dart';
|
||||
|
||||
/* Linear search (array) */
|
||||
int linearSearchArray(List<int> nums, int target) {
|
||||
// Traverse array
|
||||
for (int i = 0; i < nums.length; i++) {
|
||||
// Found the target element, return its index
|
||||
if (nums[i] == target) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
// Target element not found, return -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Linear search (linked list) */
|
||||
ListNode? linearSearchList(ListNode? head, int target) {
|
||||
// Traverse the linked list
|
||||
while (head != null) {
|
||||
// Found the target node, return it
|
||||
if (head.val == target) return head;
|
||||
head = head.next;
|
||||
}
|
||||
// Target element not found, return null
|
||||
return null;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
int target = 3;
|
||||
|
||||
/* Perform linear search in array */
|
||||
List<int> nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8];
|
||||
int index = linearSearchArray(nums, target);
|
||||
print('Index of target element 3 = $index');
|
||||
|
||||
/* Perform linear search in linked list */
|
||||
ListNode? head = listToLinkedList(nums);
|
||||
ListNode? node = linearSearchList(head, target);
|
||||
print('Node object corresponding to target node value 3 is $node');
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* File: two_sum.dart
|
||||
* Created Time: 2023-2-11
|
||||
* Author: Jefferson (JeffersonHuang77@gmail.com)
|
||||
*/
|
||||
|
||||
import 'dart:collection';
|
||||
|
||||
/* Method 1: Brute force enumeration */
|
||||
List<int> twoSumBruteForce(List<int> nums, int target) {
|
||||
int size = nums.length;
|
||||
// Two nested loops, time complexity is O(n^2)
|
||||
for (var i = 0; i < size - 1; i++) {
|
||||
for (var j = i + 1; j < size; j++) {
|
||||
if (nums[i] + nums[j] == target) return [i, j];
|
||||
}
|
||||
}
|
||||
return [0];
|
||||
}
|
||||
|
||||
/* Method 2: Auxiliary hash table */
|
||||
List<int> twoSumHashTable(List<int> nums, int target) {
|
||||
int size = nums.length;
|
||||
// Auxiliary hash table, space complexity is O(n)
|
||||
Map<int, int> dic = HashMap();
|
||||
// Single loop, time complexity is O(n)
|
||||
for (var i = 0; i < size; i++) {
|
||||
if (dic.containsKey(target - nums[i])) {
|
||||
return [dic[target - nums[i]]!, i];
|
||||
}
|
||||
dic.putIfAbsent(nums[i], () => i);
|
||||
}
|
||||
return [0];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
// ======= Test Case =======
|
||||
List<int> nums = [2, 7, 11, 15];
|
||||
int target = 13;
|
||||
|
||||
// ====== Driver Code ======
|
||||
// Method 1
|
||||
List<int> res = twoSumBruteForce(nums, target);
|
||||
print('Method 1 res = $res');
|
||||
// Method 2
|
||||
res = twoSumHashTable(nums, target);
|
||||
print('Method 2 res = $res');
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* File: bubble_sort.dart
|
||||
* Created Time: 2023-02-14
|
||||
* Author: what-is-me (whatisme@outlook.jp)
|
||||
*/
|
||||
|
||||
/* Bubble sort */
|
||||
void bubbleSort(List<int> nums) {
|
||||
// Outer loop: unsorted range is [0, i]
|
||||
for (int i = nums.length - 1; i > 0; i--) {
|
||||
// Inner loop: swap the largest element in the unsorted range [0, i] to the rightmost end of that range
|
||||
for (int j = 0; j < i; j++) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// Swap nums[j] and nums[j + 1]
|
||||
int tmp = nums[j];
|
||||
nums[j] = nums[j + 1];
|
||||
nums[j + 1] = tmp;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Bubble sort (flag optimization) */
|
||||
void bubbleSortWithFlag(List<int> nums) {
|
||||
// Outer loop: unsorted range is [0, i]
|
||||
for (int i = nums.length - 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
|
||||
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;
|
||||
flag = true; // Record element swap
|
||||
}
|
||||
}
|
||||
if (!flag) break; // No elements were swapped in this round of "bubbling", exit directly
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
List<int> nums = [4, 1, 3, 1, 5, 2];
|
||||
bubbleSort(nums);
|
||||
print("After bubble sort, nums = $nums");
|
||||
|
||||
List<int> nums1 = [4, 1, 3, 1, 5, 2];
|
||||
bubbleSortWithFlag(nums1);
|
||||
print("After bubble sort, nums1 = $nums1");
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* File: bucket_sort.dart
|
||||
* Created Time: 2023-05-12
|
||||
* Author: Jefferson (JeffersonHuang77@gmail.com)
|
||||
*/
|
||||
|
||||
/* Bucket sort */
|
||||
void bucketSort(List<double> nums) {
|
||||
// Initialize k = n/2 buckets, expected to allocate 2 elements per bucket
|
||||
int k = nums.length ~/ 2;
|
||||
List<List<double>> buckets = List.generate(k, (index) => []);
|
||||
|
||||
// 1. Distribute array elements into various buckets
|
||||
for (double _num in nums) {
|
||||
// Input data range is [0, 1), use _num * k to map to index range [0, k-1]
|
||||
int i = (_num * k).toInt();
|
||||
// Add _num to bucket bucket_idx
|
||||
buckets[i].add(_num);
|
||||
}
|
||||
// 2. Sort each bucket
|
||||
for (List<double> bucket in buckets) {
|
||||
bucket.sort();
|
||||
}
|
||||
// 3. Traverse buckets to merge results
|
||||
int i = 0;
|
||||
for (List<double> bucket in buckets) {
|
||||
for (double _num in bucket) {
|
||||
nums[i++] = _num;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code*/
|
||||
void main() {
|
||||
// Assume input data is floating point, interval [0, 1)
|
||||
final nums = [0.49, 0.96, 0.82, 0.09, 0.57, 0.43, 0.91, 0.75, 0.15, 0.37];
|
||||
bucketSort(nums);
|
||||
print('After bucket sort, nums = $nums');
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* File: counting_sort.dart
|
||||
* Created Time: 2023-05-12
|
||||
* Author: Jefferson (JeffersonHuang77@gmail.com)
|
||||
*/
|
||||
import 'dart:math';
|
||||
|
||||
/* Counting sort */
|
||||
// Simple implementation, cannot be used for sorting objects
|
||||
void countingSortNaive(List<int> nums) {
|
||||
// 1. Count the maximum element m in the array
|
||||
int m = 0;
|
||||
for (int _num in nums) {
|
||||
m = max(m, _num);
|
||||
}
|
||||
// 2. Count the occurrence of each number
|
||||
// counter[_num] represents occurrence count of _num
|
||||
List<int> counter = List.filled(m + 1, 0);
|
||||
for (int _num in nums) {
|
||||
counter[_num]++;
|
||||
}
|
||||
// 3. Traverse counter, filling each element back into the original array nums
|
||||
int i = 0;
|
||||
for (int _num = 0; _num < m + 1; _num++) {
|
||||
for (int j = 0; j < counter[_num]; j++, i++) {
|
||||
nums[i] = _num;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Counting sort */
|
||||
// Complete implementation, can sort objects and is a stable sort
|
||||
void countingSort(List<int> nums) {
|
||||
// 1. Count the maximum element m in the array
|
||||
int m = 0;
|
||||
for (int _num in nums) {
|
||||
m = max(m, _num);
|
||||
}
|
||||
// 2. Count the occurrence of each number
|
||||
// counter[_num] represents occurrence count of _num
|
||||
List<int> counter = List.filled(m + 1, 0);
|
||||
for (int _num in nums) {
|
||||
counter[_num]++;
|
||||
}
|
||||
// 3. Calculate the prefix sum of counter, converting "occurrence count" to "tail index"
|
||||
// That is, counter[_num]-1 is the last occurrence index 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
|
||||
int n = nums.length;
|
||||
List<int> res = List.filled(n, 0);
|
||||
for (int i = n - 1; i >= 0; i--) {
|
||||
int _num = nums[i];
|
||||
res[counter[_num] - 1] = _num; // Place _num at corresponding index
|
||||
counter[_num]--; // Decrement prefix sum by 1 to get next placement index for _num
|
||||
}
|
||||
// Use result array res to overwrite the original array nums
|
||||
nums.setAll(0, res);
|
||||
}
|
||||
|
||||
/* Driver Code*/
|
||||
void main() {
|
||||
final nums = [1, 0, 1, 2, 0, 4, 0, 2, 2, 4];
|
||||
countingSortNaive(nums);
|
||||
print('After counting sort (cannot sort objects), nums = $nums');
|
||||
|
||||
final nums1 = [1, 0, 1, 2, 0, 4, 0, 2, 2, 4];
|
||||
countingSort(nums1);
|
||||
print('After counting sort, nums1 = $nums1');
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* File: heap_sort.dart
|
||||
* Created Time: 2023-06-01
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Heap length is n, start heapifying node i, from top to bottom */
|
||||
void siftDown(List<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
|
||||
int l = 2 * i + 1;
|
||||
int r = 2 * i + 2;
|
||||
int ma = i;
|
||||
if (l < n && nums[l] > nums[ma]) ma = l;
|
||||
if (r < n && nums[r] > nums[ma]) ma = r;
|
||||
// Swap two nodes
|
||||
if (ma == i) break;
|
||||
// Swap two nodes
|
||||
int temp = nums[i];
|
||||
nums[i] = nums[ma];
|
||||
nums[ma] = temp;
|
||||
// Loop downwards heapification
|
||||
i = ma;
|
||||
}
|
||||
}
|
||||
|
||||
/* Heap sort */
|
||||
void heapSort(List<int> nums) {
|
||||
// Build heap operation: heapify all nodes except leaves
|
||||
for (int i = nums.length ~/ 2 - 1; i >= 0; i--) {
|
||||
siftDown(nums, nums.length, i);
|
||||
}
|
||||
// Extract the largest element from the heap and repeat for n-1 rounds
|
||||
for (int i = nums.length - 1; i > 0; i--) {
|
||||
// Delete node
|
||||
int tmp = nums[0];
|
||||
nums[0] = nums[i];
|
||||
nums[i] = tmp;
|
||||
// Start heapifying the root node, from top to bottom
|
||||
siftDown(nums, i, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
List<int> nums = [4, 1, 3, 1, 5, 2];
|
||||
heapSort(nums);
|
||||
print("After heap sort, nums = $nums");
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* File: insertion_sort.dart
|
||||
* Created Time: 2023-02-14
|
||||
* Author: what-is-me (whatisme@outlook.jp)
|
||||
*/
|
||||
|
||||
/* Insertion sort */
|
||||
void insertionSort(List<int> nums) {
|
||||
// Outer loop: sorted interval is [0, i-1]
|
||||
for (int i = 1; i < nums.length; i++) {
|
||||
int base = nums[i], j = i - 1;
|
||||
// Inner loop: insert base into the correct position within the sorted interval [0, i-1]
|
||||
while (j >= 0 && nums[j] > base) {
|
||||
nums[j + 1] = nums[j]; // Move nums[j] to the right by one position
|
||||
j--;
|
||||
}
|
||||
nums[j + 1] = base; // Assign base to the correct position
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
List<int> nums = [4, 1, 3, 1, 5, 2];
|
||||
insertionSort(nums);
|
||||
print("After insertion sort, nums = $nums");
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* File: merge_sort.dart
|
||||
* Created Time: 2023-02-14
|
||||
* Author: what-is-me (whatisme@outlook.jp)
|
||||
*/
|
||||
|
||||
/* Merge left subarray and right subarray */
|
||||
void merge(List<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
|
||||
List<int> tmp = List.filled(right - left + 1, 0);
|
||||
// Initialize the start 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 (i <= mid && j <= right) {
|
||||
if (nums[i] <= nums[j])
|
||||
tmp[k++] = nums[i++];
|
||||
else
|
||||
tmp[k++] = nums[j++];
|
||||
}
|
||||
// Copy the remaining elements of the left and right subarrays into the temporary array
|
||||
while (i <= mid) {
|
||||
tmp[k++] = nums[i++];
|
||||
}
|
||||
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
|
||||
for (k = 0; k < tmp.length; k++) {
|
||||
nums[left + k] = tmp[k];
|
||||
}
|
||||
}
|
||||
|
||||
/* Merge sort */
|
||||
void mergeSort(List<int> nums, int left, int right) {
|
||||
// Termination condition
|
||||
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
|
||||
merge(nums, left, mid, right);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
/* Merge sort */
|
||||
List<int> nums = [7, 3, 2, 6, 0, 1, 5, 4];
|
||||
mergeSort(nums, 0, nums.length - 1);
|
||||
print("After merge sort, nums = $nums");
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* File: quick_sort.dart
|
||||
* Created Time: 2023-02-14
|
||||
* Author: what-is-me (whatisme@outlook.jp)
|
||||
*/
|
||||
|
||||
/* Quick sort class */
|
||||
class QuickSort {
|
||||
/* Swap elements */
|
||||
static void _swap(List<int> nums, int i, int j) {
|
||||
int tmp = nums[i];
|
||||
nums[i] = nums[j];
|
||||
nums[j] = tmp;
|
||||
}
|
||||
|
||||
/* Sentinel partition */
|
||||
static int _partition(List<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
|
||||
while (i < j && nums[i] <= nums[left]) i++; // Search from left to right for the first element greater than the pivot
|
||||
_swap(nums, i, j); // Swap these two elements
|
||||
}
|
||||
_swap(nums, i, left); // Swap the pivot to the boundary between the two subarrays
|
||||
return i; // Return the index of the pivot
|
||||
}
|
||||
|
||||
/* Quick sort */
|
||||
static void quickSort(List<int> nums, int left, int right) {
|
||||
// Terminate recursion when subarray length is 1
|
||||
if (left >= right) return;
|
||||
// Sentinel partition
|
||||
int pivot = _partition(nums, left, right);
|
||||
// Recursively process the left subarray and right subarray
|
||||
quickSort(nums, left, pivot - 1);
|
||||
quickSort(nums, pivot + 1, right);
|
||||
}
|
||||
}
|
||||
|
||||
/* Quick sort class (median pivot optimization) */
|
||||
class QuickSortMedian {
|
||||
/* Swap elements */
|
||||
static void _swap(List<int> nums, int i, int j) {
|
||||
int tmp = nums[i];
|
||||
nums[i] = nums[j];
|
||||
nums[j] = tmp;
|
||||
}
|
||||
|
||||
/* Select the median of three candidate elements */
|
||||
static int _medianThree(List<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
|
||||
if ((m <= l && l <= r) || (r <= l && l <= m))
|
||||
return left; // l is between m and r
|
||||
return right;
|
||||
}
|
||||
|
||||
/* Sentinel partition (median of three) */
|
||||
static int _partition(List<int> nums, int left, int right) {
|
||||
// Select the median of three candidate elements
|
||||
int med = _medianThree(nums, left, (left + right) ~/ 2, right);
|
||||
// Swap the median to the array's leftmost position
|
||||
_swap(nums, left, med);
|
||||
// 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
|
||||
while (i < j && nums[i] <= nums[left]) i++; // Search from left to right for the first element greater than the pivot
|
||||
_swap(nums, i, j); // Swap these two elements
|
||||
}
|
||||
_swap(nums, i, left); // Swap the pivot to the boundary between the two subarrays
|
||||
return i; // Return the index of the pivot
|
||||
}
|
||||
|
||||
/* Quick sort */
|
||||
static void quickSort(List<int> nums, int left, int right) {
|
||||
// Terminate recursion when subarray length is 1
|
||||
if (left >= right) return;
|
||||
// Sentinel partition
|
||||
int pivot = _partition(nums, left, right);
|
||||
// Recursively process the left subarray and right subarray
|
||||
quickSort(nums, left, pivot - 1);
|
||||
quickSort(nums, pivot + 1, right);
|
||||
}
|
||||
}
|
||||
|
||||
/* Quick sort class (recursion depth optimization) */
|
||||
class QuickSortTailCall {
|
||||
/* Swap elements */
|
||||
static void _swap(List<int> nums, int i, int j) {
|
||||
int tmp = nums[i];
|
||||
nums[i] = nums[j];
|
||||
nums[j] = tmp;
|
||||
}
|
||||
|
||||
/* Sentinel partition */
|
||||
static int _partition(List<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
|
||||
while (i < j && nums[i] <= nums[left]) i++; // Search from left to right for the first element greater than the pivot
|
||||
_swap(nums, i, j); // Swap these two elements
|
||||
}
|
||||
_swap(nums, i, left); // Swap the pivot to the boundary between the two subarrays
|
||||
return i; // Return the index of the pivot
|
||||
}
|
||||
|
||||
/* Quick sort (recursion depth optimization) */
|
||||
static void quickSort(List<int> nums, int left, int right) {
|
||||
// Terminate when subarray length is 1
|
||||
while (left < right) {
|
||||
// Sentinel partition operation
|
||||
int pivot = _partition(nums, left, right);
|
||||
// Perform quick sort on 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]
|
||||
} else {
|
||||
quickSort(nums, pivot + 1, right); // Recursively sort the right subarray
|
||||
right = pivot - 1; // Remaining unsorted interval is [left, pivot - 1]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
/* Quick sort */
|
||||
List<int> nums = [2, 4, 1, 0, 3, 5];
|
||||
QuickSort.quickSort(nums, 0, nums.length - 1);
|
||||
print("After quick sort, nums = $nums");
|
||||
|
||||
/* Quick sort (recursion depth optimization) */
|
||||
List<int> nums1 = [2, 4, 1, 0, 3, 5];
|
||||
QuickSortMedian.quickSort(nums1, 0, nums1.length - 1);
|
||||
print("After quick sort (median pivot optimization), nums1 = $nums1");
|
||||
|
||||
/* Quick sort (recursion depth optimization) */
|
||||
List<int> nums2 = [2, 4, 1, 0, 3, 5];
|
||||
QuickSortTailCall.quickSort(nums2, 0, nums2.length - 1);
|
||||
print("After quick sort (recursion depth optimization), nums2 = $nums2");
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* File: radix_sort.dart
|
||||
* Created Time: 2023-02-14
|
||||
* Author: what-is-me (whatisme@outlook.jp)
|
||||
*/
|
||||
|
||||
/* Get k-th digit of element _num, where exp = 10^(k-1) */
|
||||
int digit(int _num, int exp) {
|
||||
// Passing exp instead of k can avoid repeated expensive exponentiation here
|
||||
return (_num ~/ exp) % 10;
|
||||
}
|
||||
|
||||
/* Counting sort (based on nums k-th digit) */
|
||||
void countingSortDigit(List<int> nums, int exp) {
|
||||
// Decimal digit range is 0~9, therefore need a bucket array of length 10
|
||||
List<int> counter = List<int>.filled(10, 0);
|
||||
int n = nums.length;
|
||||
// Count the occurrence of digits 0~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
|
||||
}
|
||||
// Calculate prefix sum, converting "occurrence count" into "array index"
|
||||
for (int i = 1; i < 10; i++) {
|
||||
counter[i] += counter[i - 1];
|
||||
}
|
||||
// Traverse in reverse, based on bucket statistics, place each element into res
|
||||
List<int> res = List<int>.filled(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
|
||||
res[j] = nums[i]; // Place the current element at index j
|
||||
counter[d]--; // Decrease the count of d by 1
|
||||
}
|
||||
// Use result to overwrite the original array nums
|
||||
for (int i = 0; i < n; i++) nums[i] = res[i];
|
||||
}
|
||||
|
||||
/* Radix sort */
|
||||
void radixSort(List<int> nums) {
|
||||
// Get the maximum element of the array, used to determine the maximum number of digits
|
||||
// In Dart, int length is 64 bits
|
||||
int m = -1 << 63;
|
||||
for (int _num in nums) if (_num > m) m = _num;
|
||||
// Traverse from the lowest to the highest digit
|
||||
for (int exp = 1; exp <= m; exp *= 10)
|
||||
// Perform counting sort on the k-th digit of array elements
|
||||
// k = 1 -> exp = 1
|
||||
// k = 2 -> exp = 10
|
||||
// i.e., exp = 10^(k-1)
|
||||
countingSortDigit(nums, exp);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
// Radix sort
|
||||
List<int> nums = [
|
||||
10546151,
|
||||
35663510,
|
||||
42865989,
|
||||
34862445,
|
||||
81883077,
|
||||
88906420,
|
||||
72429244,
|
||||
30524779,
|
||||
82060337,
|
||||
63832996
|
||||
];
|
||||
radixSort(nums);
|
||||
print("After radix sort, nums = $nums");
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* File: selection_sort.dart
|
||||
* Created Time: 2023-06-01
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Selection sort */
|
||||
void selectionSort(List<int> nums) {
|
||||
int n = nums.length;
|
||||
// Outer loop: unsorted interval is [i, n-1]
|
||||
for (int i = 0; i < n - 1; i++) {
|
||||
// Inner loop: find the smallest element within the unsorted interval
|
||||
int k = i;
|
||||
for (int j = i + 1; j < n; j++) {
|
||||
if (nums[j] < nums[k]) k = j; // Record the index of the smallest element
|
||||
}
|
||||
// Swap the smallest element with the first element of the unsorted interval
|
||||
int temp = nums[i];
|
||||
nums[i] = nums[k];
|
||||
nums[k] = temp;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
List<int> nums = [4, 1, 3, 1, 5, 2];
|
||||
selectionSort(nums);
|
||||
print("After selection sort, nums = $nums");
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* File: array_deque.dart
|
||||
* Created Time: 2023-03-28
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Double-ended queue based on circular array implementation */
|
||||
class ArrayDeque {
|
||||
late List<int> _nums; // Array for storing double-ended queue elements
|
||||
late int _front; // Front pointer, points to the front of the queue element
|
||||
late int _queSize; // Double-ended queue length
|
||||
|
||||
/* Constructor */
|
||||
ArrayDeque(int capacity) {
|
||||
this._nums = List.filled(capacity, 0);
|
||||
this._front = this._queSize = 0;
|
||||
}
|
||||
|
||||
/* Get the capacity of the double-ended queue */
|
||||
int capacity() {
|
||||
return _nums.length;
|
||||
}
|
||||
|
||||
/* Get the length of the double-ended queue */
|
||||
int size() {
|
||||
return _queSize;
|
||||
}
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
bool isEmpty() {
|
||||
return _queSize == 0;
|
||||
}
|
||||
|
||||
/* Calculate circular array index */
|
||||
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
|
||||
return (i + capacity()) % capacity();
|
||||
}
|
||||
|
||||
/* Front of the queue enqueue */
|
||||
void pushFirst(int _num) {
|
||||
if (_queSize == capacity()) {
|
||||
throw Exception("Double-ended queue is full");
|
||||
}
|
||||
// Use modulo operation to wrap front around to the tail after passing the head of the array
|
||||
// Use modulo operation to wrap _front from array head back to tail
|
||||
_front = index(_front - 1);
|
||||
// Add _num to queue front
|
||||
_nums[_front] = _num;
|
||||
_queSize++;
|
||||
}
|
||||
|
||||
/* Rear of the queue enqueue */
|
||||
void pushLast(int _num) {
|
||||
if (_queSize == capacity()) {
|
||||
throw Exception("Double-ended queue is full");
|
||||
}
|
||||
// Use modulo operation to wrap rear around to the head after passing the tail of the array
|
||||
int rear = index(_front + _queSize);
|
||||
// Add _num to queue rear
|
||||
_nums[rear] = _num;
|
||||
_queSize++;
|
||||
}
|
||||
|
||||
/* Rear of the queue dequeue */
|
||||
int popFirst() {
|
||||
int _num = peekFirst();
|
||||
// Move front pointer right by one
|
||||
_front = index(_front + 1);
|
||||
_queSize--;
|
||||
return _num;
|
||||
}
|
||||
|
||||
/* Access rear of the queue element */
|
||||
int popLast() {
|
||||
int _num = peekLast();
|
||||
_queSize--;
|
||||
return _num;
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
int peekFirst() {
|
||||
if (isEmpty()) {
|
||||
throw Exception("Deque is empty");
|
||||
}
|
||||
return _nums[_front];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
int peekLast() {
|
||||
if (isEmpty()) {
|
||||
throw Exception("Deque is empty");
|
||||
}
|
||||
// Initialize double-ended queue
|
||||
int last = index(_front + _queSize - 1);
|
||||
return _nums[last];
|
||||
}
|
||||
|
||||
/* Return array for printing */
|
||||
List<int> toArray() {
|
||||
// Elements enqueue
|
||||
List<int> res = List.filled(_queSize, 0);
|
||||
for (int i = 0, j = _front; i < _queSize; i++, j++) {
|
||||
res[i] = _nums[index(j)];
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
/* Get the length of the double-ended queue */
|
||||
final ArrayDeque deque = ArrayDeque(10);
|
||||
deque.pushLast(3);
|
||||
deque.pushLast(2);
|
||||
deque.pushLast(5);
|
||||
print("Deque deque = ${deque.toArray()}");
|
||||
|
||||
/* Update element */
|
||||
final int peekFirst = deque.peekFirst();
|
||||
print("Front element peekFirst = $peekFirst");
|
||||
final int peekLast = deque.peekLast();
|
||||
print("Rear element peekLast = $peekLast");
|
||||
|
||||
/* Elements enqueue */
|
||||
deque.pushLast(4);
|
||||
print("After element 4 enqueues at rear, deque = ${deque.toArray()}");
|
||||
deque.pushFirst(1);
|
||||
print("After element 1 enqueues at front, deque = ${deque.toArray()}");
|
||||
|
||||
/* Element dequeue */
|
||||
final int popLast = deque.popLast();
|
||||
print("Dequeue rear element = $popLast, after rear dequeue deque = ${deque.toArray()}");
|
||||
final int popFirst = deque.popFirst();
|
||||
print("Dequeue front element = $popFirst, after front dequeue deque = ${deque.toArray()}");
|
||||
|
||||
/* Get the length of the double-ended queue */
|
||||
final int size = deque.size();
|
||||
print("Deque length size = $size");
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
final bool isEmpty = deque.isEmpty();
|
||||
print("Is deque empty = $isEmpty");
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* File: array_queue.dart
|
||||
* Created Time: 2023-03-28
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Queue based on circular array implementation */
|
||||
class ArrayQueue {
|
||||
late List<int> _nums; // Array for storing queue elements
|
||||
late int _front; // Front pointer, points to the front of the queue element
|
||||
late int _queSize; // Queue length
|
||||
|
||||
ArrayQueue(int capacity) {
|
||||
_nums = List.filled(capacity, 0);
|
||||
_front = _queSize = 0;
|
||||
}
|
||||
|
||||
/* Get the capacity of the queue */
|
||||
int capaCity() {
|
||||
return _nums.length;
|
||||
}
|
||||
|
||||
/* Get the length of the queue */
|
||||
int size() {
|
||||
return _queSize;
|
||||
}
|
||||
|
||||
/* Check if the queue is empty */
|
||||
bool isEmpty() {
|
||||
return _queSize == 0;
|
||||
}
|
||||
|
||||
/* Enqueue */
|
||||
void push(int _num) {
|
||||
if (_queSize == capaCity()) {
|
||||
throw Exception("Queue is full");
|
||||
}
|
||||
// Use modulo operation to wrap rear around to the head after passing the tail of the array
|
||||
// Add num to the rear of the queue
|
||||
int rear = (_front + _queSize) % capaCity();
|
||||
// Add _num to queue rear
|
||||
_nums[rear] = _num;
|
||||
_queSize++;
|
||||
}
|
||||
|
||||
/* Dequeue */
|
||||
int pop() {
|
||||
int _num = peek();
|
||||
// Move front pointer backward by one position, if it passes the tail, return to array head
|
||||
_front = (_front + 1) % capaCity();
|
||||
_queSize--;
|
||||
return _num;
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
int peek() {
|
||||
if (isEmpty()) {
|
||||
throw Exception("Queue is empty");
|
||||
}
|
||||
return _nums[_front];
|
||||
}
|
||||
|
||||
/* Return Array */
|
||||
List<int> toArray() {
|
||||
// Elements enqueue
|
||||
final List<int> res = List.filled(_queSize, 0);
|
||||
for (int i = 0, j = _front; i < _queSize; i++, j++) {
|
||||
res[i] = _nums[j % capaCity()];
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
/* Access front of the queue element */
|
||||
final int capacity = 10;
|
||||
final ArrayQueue queue = ArrayQueue(capacity);
|
||||
|
||||
/* Elements enqueue */
|
||||
queue.push(1);
|
||||
queue.push(3);
|
||||
queue.push(2);
|
||||
queue.push(5);
|
||||
queue.push(4);
|
||||
print("Queue queue = ${queue.toArray()}");
|
||||
|
||||
/* Return list for printing */
|
||||
final int peek = queue.peek();
|
||||
print("Front element peek = $peek");
|
||||
|
||||
/* Element dequeue */
|
||||
final int pop = queue.pop();
|
||||
print("Dequeue element pop = $pop, after dequeue queue = ${queue.toArray()}");
|
||||
|
||||
/* Get queue length */
|
||||
final int size = queue.size();
|
||||
print("Queue length size = $size");
|
||||
|
||||
/* Check if the queue is empty */
|
||||
final bool isEmpty = queue.isEmpty();
|
||||
print("Is queue empty = $isEmpty");
|
||||
|
||||
/* Test circular array */
|
||||
for (int i = 0; i < 10; i++) {
|
||||
queue.push(i);
|
||||
queue.pop();
|
||||
print("After round $i enqueue + dequeue, queue = ${queue.toArray()}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* File: array_stack.dart
|
||||
* Created Time: 2023-03-28
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Stack based on array implementation */
|
||||
class ArrayStack {
|
||||
late List<int> _stack;
|
||||
ArrayStack() {
|
||||
_stack = [];
|
||||
}
|
||||
|
||||
/* Get the length of the stack */
|
||||
int size() {
|
||||
return _stack.length;
|
||||
}
|
||||
|
||||
/* Check if the stack is empty */
|
||||
bool isEmpty() {
|
||||
return _stack.isEmpty;
|
||||
}
|
||||
|
||||
/* Push */
|
||||
void push(int _num) {
|
||||
_stack.add(_num);
|
||||
}
|
||||
|
||||
/* Pop */
|
||||
int pop() {
|
||||
if (isEmpty()) {
|
||||
throw Exception("Stack is empty");
|
||||
}
|
||||
return _stack.removeLast();
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
int peek() {
|
||||
if (isEmpty()) {
|
||||
throw Exception("Stack is empty");
|
||||
}
|
||||
return _stack.last;
|
||||
}
|
||||
|
||||
/* Convert stack to Array and return */
|
||||
List<int> toArray() => _stack;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
/* Access top of the stack element */
|
||||
final ArrayStack stack = ArrayStack();
|
||||
|
||||
/* Elements push onto stack */
|
||||
stack.push(1);
|
||||
stack.push(3);
|
||||
stack.push(2);
|
||||
stack.push(5);
|
||||
stack.push(4);
|
||||
print("Stack stack = ${stack.toArray()}");
|
||||
|
||||
/* Return list for printing */
|
||||
final int peek = stack.peek();
|
||||
print("Top element peek = $peek");
|
||||
|
||||
/* Element pop from stack */
|
||||
final int pop = stack.pop();
|
||||
print("Pop element pop = $pop, after pop stack = ${stack.toArray()}");
|
||||
|
||||
/* Get the length of the stack */
|
||||
final int size = stack.size();
|
||||
print("Stack length size = $size");
|
||||
|
||||
/* Check if empty */
|
||||
final bool isEmpty = stack.isEmpty();
|
||||
print("Is stack empty = $isEmpty");
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* File: deque.dart
|
||||
* Created Time: 2023-03-28
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import 'dart:collection';
|
||||
|
||||
void main() {
|
||||
/* Get the length of the double-ended queue */
|
||||
final Queue<int> deque = Queue();
|
||||
deque.addFirst(3);
|
||||
deque.addLast(2);
|
||||
deque.addLast(5);
|
||||
print("Deque deque = $deque");
|
||||
|
||||
/* Update element */
|
||||
final int peekFirst = deque.first;
|
||||
print("Front element peekFirst = $peekFirst");
|
||||
final int peekLast = deque.last;
|
||||
print("Rear element peekLast = $peekLast");
|
||||
|
||||
/* Elements enqueue */
|
||||
deque.addLast(4);
|
||||
print("After element 4 enqueues at rear, deque = $deque");
|
||||
deque.addFirst(1);
|
||||
print("After element 1 enqueues at front, deque = $deque");
|
||||
|
||||
/* Element dequeue */
|
||||
final int popLast = deque.removeLast();
|
||||
print("Dequeue rear element = $popLast, after rear dequeue deque = $deque");
|
||||
final int popFirst = deque.removeFirst();
|
||||
print("Dequeue front element = $popFirst, after front dequeue deque = $deque");
|
||||
|
||||
/* Get the length of the double-ended queue */
|
||||
final int size = deque.length;
|
||||
print("Deque length size = $size");
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
final bool isEmpty = deque.isEmpty;
|
||||
print("Is deque empty = $isEmpty");
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
/**
|
||||
* File: linkedlist_deque.dart
|
||||
* Created Time: 2023-03-28
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Doubly linked list node */
|
||||
class ListNode {
|
||||
int val; // Node value
|
||||
ListNode? next; // Successor node reference
|
||||
ListNode? prev; // Predecessor node reference
|
||||
|
||||
ListNode(this.val, {this.next, this.prev});
|
||||
}
|
||||
|
||||
/* Deque implemented based on doubly linked list */
|
||||
class LinkedListDeque {
|
||||
late ListNode? _front; // Head node _front
|
||||
late ListNode? _rear; // Tail node _rear
|
||||
int _queSize = 0; // Length of the double-ended queue
|
||||
|
||||
LinkedListDeque() {
|
||||
this._front = null;
|
||||
this._rear = null;
|
||||
}
|
||||
|
||||
/* Get deque length */
|
||||
int size() {
|
||||
return this._queSize;
|
||||
}
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
bool isEmpty() {
|
||||
return size() == 0;
|
||||
}
|
||||
|
||||
/* Enqueue operation */
|
||||
void push(int _num, bool isFront) {
|
||||
final ListNode node = ListNode(_num);
|
||||
if (isEmpty()) {
|
||||
// If list is empty, let both _front and _rear point to node
|
||||
_front = _rear = node;
|
||||
} else if (isFront) {
|
||||
// Front of the queue enqueue operation
|
||||
// Add node to the head of the linked list
|
||||
_front!.prev = node;
|
||||
node.next = _front;
|
||||
_front = node; // Update head node
|
||||
} else {
|
||||
// Rear of the queue enqueue operation
|
||||
// Add node to the tail of the linked list
|
||||
_rear!.next = node;
|
||||
node.prev = _rear;
|
||||
_rear = node; // Update tail node
|
||||
}
|
||||
_queSize++; // Update queue length
|
||||
}
|
||||
|
||||
/* Front of the queue enqueue */
|
||||
void pushFirst(int _num) {
|
||||
push(_num, true);
|
||||
}
|
||||
|
||||
/* Rear of the queue enqueue */
|
||||
void pushLast(int _num) {
|
||||
push(_num, false);
|
||||
}
|
||||
|
||||
/* Dequeue operation */
|
||||
int? pop(bool isFront) {
|
||||
// If queue is empty, return null directly
|
||||
if (isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
final int val;
|
||||
if (isFront) {
|
||||
// Temporarily store head node value
|
||||
val = _front!.val; // Delete head node
|
||||
// Delete head node
|
||||
ListNode? fNext = _front!.next;
|
||||
if (fNext != null) {
|
||||
fNext.prev = null;
|
||||
_front!.next = null;
|
||||
}
|
||||
_front = fNext; // Update head node
|
||||
} else {
|
||||
// Temporarily store tail node value
|
||||
val = _rear!.val; // Delete tail node
|
||||
// Update tail node
|
||||
ListNode? rPrev = _rear!.prev;
|
||||
if (rPrev != null) {
|
||||
rPrev.next = null;
|
||||
_rear!.prev = null;
|
||||
}
|
||||
_rear = rPrev; // Update tail node
|
||||
}
|
||||
_queSize--; // Update queue length
|
||||
return val;
|
||||
}
|
||||
|
||||
/* Rear of the queue dequeue */
|
||||
int? popFirst() {
|
||||
return pop(true);
|
||||
}
|
||||
|
||||
/* Access rear of the queue element */
|
||||
int? popLast() {
|
||||
return pop(false);
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
int? peekFirst() {
|
||||
return _front?.val;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
int? peekLast() {
|
||||
return _rear?.val;
|
||||
}
|
||||
|
||||
/* Return array for printing */
|
||||
List<int> toArray() {
|
||||
ListNode? node = _front;
|
||||
final List<int> res = [];
|
||||
for (int i = 0; i < _queSize; i++) {
|
||||
res.add(node!.val);
|
||||
node = node.next;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
/* Get the length of the double-ended queue */
|
||||
final LinkedListDeque deque = LinkedListDeque();
|
||||
deque.pushLast(3);
|
||||
deque.pushLast(2);
|
||||
deque.pushLast(5);
|
||||
print("Deque deque = ${deque.toArray()}");
|
||||
|
||||
/* Update element */
|
||||
int? peekFirst = deque.peekFirst();
|
||||
print("Front element peekFirst = $peekFirst");
|
||||
int? peekLast = deque.peekLast();
|
||||
print("Rear element peekLast = $peekLast");
|
||||
|
||||
/* Elements enqueue */
|
||||
deque.pushLast(4);
|
||||
print("After element 4 enqueues at rear, deque = ${deque.toArray()}");
|
||||
deque.pushFirst(1);
|
||||
print("After element 1 enqueues at front, deque = ${deque.toArray()}");
|
||||
|
||||
/* Element dequeue */
|
||||
int? popLast = deque.popLast();
|
||||
print("Dequeue rear element = $popLast, after rear dequeue deque = ${deque.toArray()}");
|
||||
int? popFirst = deque.popFirst();
|
||||
print("Dequeue front element = $popFirst, after front dequeue deque = ${deque.toArray()}");
|
||||
|
||||
/* Get the length of the double-ended queue */
|
||||
int size = deque.size();
|
||||
print("Deque length size = $size");
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
bool isEmpty = deque.isEmpty();
|
||||
print("Is deque empty = $isEmpty");
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* File: linkedlist_queue.dart
|
||||
* Created Time: 2023-03-28
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import '../utils/list_node.dart';
|
||||
|
||||
/* Queue based on linked list implementation */
|
||||
class LinkedListQueue {
|
||||
ListNode? _front; // Head node _front
|
||||
ListNode? _rear; // Tail node _rear
|
||||
int _queSize = 0; // Queue length
|
||||
|
||||
LinkedListQueue() {
|
||||
_front = null;
|
||||
_rear = null;
|
||||
}
|
||||
|
||||
/* Get the length of the queue */
|
||||
int size() {
|
||||
return _queSize;
|
||||
}
|
||||
|
||||
/* Check if the queue is empty */
|
||||
bool isEmpty() {
|
||||
return _queSize == 0;
|
||||
}
|
||||
|
||||
/* Enqueue */
|
||||
void push(int _num) {
|
||||
// Add _num after tail node
|
||||
final node = ListNode(_num);
|
||||
// If the queue is empty, make both front and rear point to the node
|
||||
if (_front == null) {
|
||||
_front = node;
|
||||
_rear = node;
|
||||
} else {
|
||||
// If the queue is not empty, add the node after the tail node
|
||||
_rear!.next = node;
|
||||
_rear = node;
|
||||
}
|
||||
_queSize++;
|
||||
}
|
||||
|
||||
/* Dequeue */
|
||||
int pop() {
|
||||
final int _num = peek();
|
||||
// Delete head node
|
||||
_front = _front!.next;
|
||||
_queSize--;
|
||||
return _num;
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
int peek() {
|
||||
if (_queSize == 0) {
|
||||
throw Exception('Queue is empty');
|
||||
}
|
||||
return _front!.val;
|
||||
}
|
||||
|
||||
/* Convert linked list to Array and return */
|
||||
List<int> toArray() {
|
||||
ListNode? node = _front;
|
||||
final List<int> queue = [];
|
||||
while (node != null) {
|
||||
queue.add(node.val);
|
||||
node = node.next;
|
||||
}
|
||||
return queue;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
/* Access front of the queue element */
|
||||
final queue = LinkedListQueue();
|
||||
|
||||
/* Elements enqueue */
|
||||
queue.push(1);
|
||||
queue.push(3);
|
||||
queue.push(2);
|
||||
queue.push(5);
|
||||
queue.push(4);
|
||||
print("Queue queue = ${queue.toArray()}");
|
||||
|
||||
/* Return list for printing */
|
||||
final int peek = queue.peek();
|
||||
print("Front element peek = $peek");
|
||||
|
||||
/* Element dequeue */
|
||||
final int pop = queue.pop();
|
||||
print("Dequeue element pop = $pop, after dequeue queue = ${queue.toArray()}");
|
||||
|
||||
/* Get the length of the queue */
|
||||
final int size = queue.size();
|
||||
print("Queue length size = $size");
|
||||
|
||||
/* Check if the queue is empty */
|
||||
final bool isEmpty = queue.isEmpty();
|
||||
print("Is queue empty = $isEmpty");
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* File: linkedlist_stack.dart
|
||||
* Created Time: 2023-03-27
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import '../utils/list_node.dart';
|
||||
|
||||
/* Stack implemented based on linked list class */
|
||||
class LinkedListStack {
|
||||
ListNode? _stackPeek; // Use head node as stack top
|
||||
int _stkSize = 0; // Stack length
|
||||
|
||||
LinkedListStack() {
|
||||
_stackPeek = null;
|
||||
}
|
||||
|
||||
/* Get the length of the stack */
|
||||
int size() {
|
||||
return _stkSize;
|
||||
}
|
||||
|
||||
/* Check if the stack is empty */
|
||||
bool isEmpty() {
|
||||
return _stkSize == 0;
|
||||
}
|
||||
|
||||
/* Push */
|
||||
void push(int _num) {
|
||||
final ListNode node = ListNode(_num);
|
||||
node.next = _stackPeek;
|
||||
_stackPeek = node;
|
||||
_stkSize++;
|
||||
}
|
||||
|
||||
/* Pop */
|
||||
int pop() {
|
||||
final int _num = peek();
|
||||
_stackPeek = _stackPeek!.next;
|
||||
_stkSize--;
|
||||
return _num;
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
int peek() {
|
||||
if (_stackPeek == null) {
|
||||
throw Exception("Stack is empty");
|
||||
}
|
||||
return _stackPeek!.val;
|
||||
}
|
||||
|
||||
/* Convert linked list to List and return */
|
||||
List<int> toList() {
|
||||
ListNode? node = _stackPeek;
|
||||
List<int> list = [];
|
||||
while (node != null) {
|
||||
list.add(node.val);
|
||||
node = node.next;
|
||||
}
|
||||
list = list.reversed.toList();
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
/* Access top of the stack element */
|
||||
final LinkedListStack stack = LinkedListStack();
|
||||
|
||||
/* Elements push onto stack */
|
||||
stack.push(1);
|
||||
stack.push(3);
|
||||
stack.push(2);
|
||||
stack.push(5);
|
||||
stack.push(4);
|
||||
print("Stack stack = ${stack.toList()}");
|
||||
|
||||
/* Return list for printing */
|
||||
final int peek = stack.peek();
|
||||
print("Top element peek = $peek");
|
||||
|
||||
/* Element pop from stack */
|
||||
final int pop = stack.pop();
|
||||
print("Pop element pop = $pop, after pop stack = ${stack.toList()}");
|
||||
|
||||
/* Get the length of the stack */
|
||||
final int size = stack.size();
|
||||
print("Stack length size = $size");
|
||||
|
||||
/* Check if empty */
|
||||
final bool isEmpty = stack.isEmpty();
|
||||
print("Is stack empty = $isEmpty");
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* File: queue.dart
|
||||
* Created Time: 2023-03-28
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import 'dart:collection';
|
||||
|
||||
void main() {
|
||||
/* Access front of the queue element */
|
||||
// In Dart, generally use Queue class as queue
|
||||
final Queue<int> queue = Queue();
|
||||
|
||||
/* Elements enqueue */
|
||||
queue.add(1);
|
||||
queue.add(3);
|
||||
queue.add(2);
|
||||
queue.add(5);
|
||||
queue.add(4);
|
||||
print("Queue queue = $queue");
|
||||
|
||||
/* Return list for printing */
|
||||
final int peek = queue.first;
|
||||
print("Front element peek = $peek");
|
||||
|
||||
/* Element dequeue */
|
||||
final int pop = queue.removeFirst();
|
||||
print("Dequeue element pop = $pop, after dequeue queue = $queue");
|
||||
|
||||
/* Get queue length */
|
||||
final int size = queue.length;
|
||||
print("Queue length size = $size");
|
||||
|
||||
/* Check if the queue is empty */
|
||||
final bool isEmpty = queue.isEmpty;
|
||||
print("Is queue empty = $isEmpty");
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* File: stack.dart
|
||||
* Created Time: 2023-03-27
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
void main() {
|
||||
/* Access top of the stack element */
|
||||
// Dart has no built-in stack class, can use List as stack
|
||||
final List<int> stack = [];
|
||||
|
||||
/* Elements push onto stack */
|
||||
stack.add(1);
|
||||
stack.add(3);
|
||||
stack.add(2);
|
||||
stack.add(5);
|
||||
stack.add(4);
|
||||
print("Stack stack = $stack");
|
||||
|
||||
/* Return list for printing */
|
||||
final int peek = stack.last;
|
||||
print("Top element peek = $peek");
|
||||
|
||||
/* Element pop from stack */
|
||||
final int pop = stack.removeLast();
|
||||
print("Pop element pop = $pop, after pop stack = $stack");
|
||||
|
||||
/* Get the length of the stack */
|
||||
final int size = stack.length;
|
||||
print("Stack length size = $size");
|
||||
|
||||
/* Check if empty */
|
||||
final bool isEmpty = stack.isEmpty;
|
||||
print("Is stack empty = $isEmpty");
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* File: array_binary_tree.dart
|
||||
* Created Time: 2023-08-15
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import '../utils/print_util.dart';
|
||||
import '../utils/tree_node.dart';
|
||||
|
||||
/* Binary tree class represented by array */
|
||||
class ArrayBinaryTree {
|
||||
late List<int?> _tree;
|
||||
|
||||
/* Constructor */
|
||||
ArrayBinaryTree(this._tree);
|
||||
|
||||
/* List capacity */
|
||||
int size() {
|
||||
return _tree.length;
|
||||
}
|
||||
|
||||
/* Get value of node at index i */
|
||||
int? val(int i) {
|
||||
// If index out of bounds, return null to represent empty position
|
||||
if (i < 0 || i >= size()) {
|
||||
return null;
|
||||
}
|
||||
return _tree[i];
|
||||
}
|
||||
|
||||
/* Get index of left child node of node at index i */
|
||||
int? left(int i) {
|
||||
return 2 * i + 1;
|
||||
}
|
||||
|
||||
/* Get index of right child node of node at index i */
|
||||
int? right(int i) {
|
||||
return 2 * i + 2;
|
||||
}
|
||||
|
||||
/* Get index of parent node of node at index i */
|
||||
int? parent(int i) {
|
||||
return (i - 1) ~/ 2;
|
||||
}
|
||||
|
||||
/* Level-order traversal */
|
||||
List<int> levelOrder() {
|
||||
List<int> res = [];
|
||||
for (int i = 0; i < size(); i++) {
|
||||
if (val(i) != null) {
|
||||
res.add(val(i)!);
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Depth-first traversal */
|
||||
void dfs(int i, String order, List<int?> res) {
|
||||
// If empty position, return
|
||||
if (val(i) == null) {
|
||||
return;
|
||||
}
|
||||
// Preorder traversal
|
||||
if (order == 'pre') {
|
||||
res.add(val(i));
|
||||
}
|
||||
dfs(left(i)!, order, res);
|
||||
// Inorder traversal
|
||||
if (order == 'in') {
|
||||
res.add(val(i));
|
||||
}
|
||||
dfs(right(i)!, order, res);
|
||||
// Postorder traversal
|
||||
if (order == 'post') {
|
||||
res.add(val(i));
|
||||
}
|
||||
}
|
||||
|
||||
/* Preorder traversal */
|
||||
List<int?> preOrder() {
|
||||
List<int?> res = [];
|
||||
dfs(0, 'pre', res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Inorder traversal */
|
||||
List<int?> inOrder() {
|
||||
List<int?> res = [];
|
||||
dfs(0, 'in', res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Postorder traversal */
|
||||
List<int?> postOrder() {
|
||||
List<int?> res = [];
|
||||
dfs(0, 'post', res);
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
// Initialize binary tree
|
||||
// Here we use a function to generate a binary tree directly from an array
|
||||
List<int?> arr = [
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
null,
|
||||
6,
|
||||
7,
|
||||
8,
|
||||
9,
|
||||
null,
|
||||
null,
|
||||
12,
|
||||
null,
|
||||
null,
|
||||
15
|
||||
];
|
||||
|
||||
TreeNode? root = listToTree(arr);
|
||||
print("\nInitialize binary tree\n");
|
||||
print("Array representation of binary tree:");
|
||||
print(arr);
|
||||
print("Linked list representation of binary tree:");
|
||||
printTree(root);
|
||||
|
||||
// Binary tree class represented by array
|
||||
ArrayBinaryTree abt = ArrayBinaryTree(arr);
|
||||
|
||||
// Access node
|
||||
int i = 1;
|
||||
int? l = abt.left(i);
|
||||
int? r = abt.right(i);
|
||||
int? p = abt.parent(i);
|
||||
print("\nCurrent node index is $i, value is ${abt.val(i)}");
|
||||
print("Its left child index is $l, value is ${(l == null ? "null" : abt.val(l))}");
|
||||
print("Its right child index is $r, value is ${(r == null ? "null" : abt.val(r))}");
|
||||
print("Its parent node index is $p, value is ${(p == null ? "null" : abt.val(p))}");
|
||||
|
||||
// Traverse tree
|
||||
List<int?> res = abt.levelOrder();
|
||||
print("\nLevel-order traversal is: $res");
|
||||
res = abt.preOrder();
|
||||
print("Pre-order traversal is $res");
|
||||
res = abt.inOrder();
|
||||
print("In-order traversal is $res");
|
||||
res = abt.postOrder();
|
||||
print("Post-order traversal is $res");
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
/**
|
||||
* File: avl_tree.dart
|
||||
* Created Time: 2023-04-04
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import 'dart:math';
|
||||
import '../utils/print_util.dart';
|
||||
import '../utils/tree_node.dart';
|
||||
|
||||
class AVLTree {
|
||||
TreeNode? root;
|
||||
|
||||
/* Constructor */
|
||||
AVLTree() {
|
||||
root = null;
|
||||
}
|
||||
|
||||
/* Get node height */
|
||||
int height(TreeNode? node) {
|
||||
// Empty node height is -1, leaf node height is 0
|
||||
return node == null ? -1 : node.height;
|
||||
}
|
||||
|
||||
/* Update node height */
|
||||
void updateHeight(TreeNode? node) {
|
||||
// Node height equals the height of the tallest subtree + 1
|
||||
node!.height = max(height(node.left), height(node.right)) + 1;
|
||||
}
|
||||
|
||||
/* Get balance factor */
|
||||
int balanceFactor(TreeNode? node) {
|
||||
// Empty node balance factor is 0
|
||||
if (node == null) return 0;
|
||||
// Node balance factor = left subtree height - right subtree height
|
||||
return height(node.left) - height(node.right);
|
||||
}
|
||||
|
||||
/* Right rotation operation */
|
||||
TreeNode? rightRotate(TreeNode? node) {
|
||||
TreeNode? child = node!.left;
|
||||
TreeNode? grandChild = child!.right;
|
||||
// Using child as pivot, rotate node to the right
|
||||
child.right = node;
|
||||
node.left = grandChild;
|
||||
// Update node height
|
||||
updateHeight(node);
|
||||
updateHeight(child);
|
||||
// Return root node of subtree after rotation
|
||||
return child;
|
||||
}
|
||||
|
||||
/* Left rotation operation */
|
||||
TreeNode? leftRotate(TreeNode? node) {
|
||||
TreeNode? child = node!.right;
|
||||
TreeNode? grandChild = child!.left;
|
||||
// Using child as pivot, rotate node to the left
|
||||
child.left = node;
|
||||
node.right = grandChild;
|
||||
// Update node height
|
||||
updateHeight(node);
|
||||
updateHeight(child);
|
||||
// Return root node of subtree after rotation
|
||||
return child;
|
||||
}
|
||||
|
||||
/* Perform rotation operation to restore balance to this subtree */
|
||||
TreeNode? rotate(TreeNode? node) {
|
||||
// Get balance factor of node
|
||||
int factor = balanceFactor(node);
|
||||
// Left-leaning tree
|
||||
if (factor > 1) {
|
||||
if (balanceFactor(node!.left) >= 0) {
|
||||
// Right rotation
|
||||
return rightRotate(node);
|
||||
} else {
|
||||
// First left rotation then right rotation
|
||||
node.left = leftRotate(node.left);
|
||||
return rightRotate(node);
|
||||
}
|
||||
}
|
||||
// Right-leaning tree
|
||||
if (factor < -1) {
|
||||
if (balanceFactor(node!.right) <= 0) {
|
||||
// Left rotation
|
||||
return leftRotate(node);
|
||||
} else {
|
||||
// First right rotation then left rotation
|
||||
node.right = rightRotate(node.right);
|
||||
return leftRotate(node);
|
||||
}
|
||||
}
|
||||
// Balanced tree, no rotation needed, return directly
|
||||
return node;
|
||||
}
|
||||
|
||||
/* Insert node */
|
||||
void insert(int val) {
|
||||
root = insertHelper(root, val);
|
||||
}
|
||||
|
||||
/* Recursively insert node (helper method) */
|
||||
TreeNode? insertHelper(TreeNode? node, int val) {
|
||||
if (node == null) return TreeNode(val);
|
||||
/* 1. Find insertion position and insert 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 */
|
||||
node = rotate(node);
|
||||
// Return root node of subtree
|
||||
return node;
|
||||
}
|
||||
|
||||
/* Remove node */
|
||||
void remove(int val) {
|
||||
root = removeHelper(root, val);
|
||||
}
|
||||
|
||||
/* Recursively delete node (helper method) */
|
||||
TreeNode? removeHelper(TreeNode? node, int val) {
|
||||
if (node == null) return null;
|
||||
/* 1. Find node and delete */
|
||||
if (val < node.val)
|
||||
node.left = removeHelper(node.left, val);
|
||||
else if (val > node.val)
|
||||
node.right = removeHelper(node.right, val);
|
||||
else {
|
||||
if (node.left == null || node.right == null) {
|
||||
TreeNode? child = node.left ?? node.right;
|
||||
// Number of child nodes = 0, delete node directly and return
|
||||
if (child == null)
|
||||
return null;
|
||||
// Number of child nodes = 1, delete node directly
|
||||
else
|
||||
node = child;
|
||||
} else {
|
||||
// Number of child nodes = 2, delete the next node in inorder traversal and replace current node with it
|
||||
TreeNode? temp = node.right;
|
||||
while (temp!.left != null) {
|
||||
temp = temp.left;
|
||||
}
|
||||
node.right = removeHelper(node.right, temp.val);
|
||||
node.val = temp.val;
|
||||
}
|
||||
}
|
||||
updateHeight(node); // Update node height
|
||||
/* 2. Perform rotation operation to restore balance to this subtree */
|
||||
node = rotate(node);
|
||||
// Return root node of subtree
|
||||
return node;
|
||||
}
|
||||
|
||||
/* Search node */
|
||||
TreeNode? search(int val) {
|
||||
TreeNode? cur = root;
|
||||
// Loop search, exit after passing leaf node
|
||||
while (cur != null) {
|
||||
// Target node is in cur's right subtree
|
||||
if (val < cur.val)
|
||||
cur = cur.left;
|
||||
// Target node is in cur's left subtree
|
||||
else if (val > cur.val)
|
||||
cur = cur.right;
|
||||
// Target node equals current node
|
||||
else
|
||||
break;
|
||||
}
|
||||
return cur;
|
||||
}
|
||||
}
|
||||
|
||||
void testInsert(AVLTree tree, int val) {
|
||||
tree.insert(val);
|
||||
print("\nAfter inserting node $val, AVL tree is");
|
||||
printTree(tree.root);
|
||||
}
|
||||
|
||||
void testRemove(AVLTree tree, int val) {
|
||||
tree.remove(val);
|
||||
print("\nAfter deleting node $val, AVL tree is");
|
||||
printTree(tree.root);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
/* Please pay attention to how the AVL tree maintains balance after inserting nodes */
|
||||
AVLTree avlTree = AVLTree();
|
||||
/* Insert node */
|
||||
// Delete nodes
|
||||
testInsert(avlTree, 1);
|
||||
testInsert(avlTree, 2);
|
||||
testInsert(avlTree, 3);
|
||||
testInsert(avlTree, 4);
|
||||
testInsert(avlTree, 5);
|
||||
testInsert(avlTree, 8);
|
||||
testInsert(avlTree, 7);
|
||||
testInsert(avlTree, 9);
|
||||
testInsert(avlTree, 10);
|
||||
testInsert(avlTree, 6);
|
||||
|
||||
/* Please pay attention to how the AVL tree maintains balance after deleting nodes */
|
||||
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
|
||||
|
||||
/* Search node */
|
||||
TreeNode? node = avlTree.search(7);
|
||||
print("\nFound node object is $node, node value = ${node!.val}");
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* File: binary_search_tree.dart
|
||||
* Created Time: 2023-04-04
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import '../utils/print_util.dart';
|
||||
import '../utils/tree_node.dart';
|
||||
|
||||
/* Binary search tree */
|
||||
class BinarySearchTree {
|
||||
late TreeNode? _root;
|
||||
|
||||
/* Constructor */
|
||||
BinarySearchTree() {
|
||||
// Initialize empty tree
|
||||
_root = null;
|
||||
}
|
||||
|
||||
/* Get root node of binary tree */
|
||||
TreeNode? getRoot() {
|
||||
return _root;
|
||||
}
|
||||
|
||||
/* Search node */
|
||||
TreeNode? search(int _num) {
|
||||
TreeNode? cur = _root;
|
||||
// Loop search, exit after passing leaf node
|
||||
while (cur != null) {
|
||||
// Target node is in cur's right subtree
|
||||
if (cur.val < _num)
|
||||
cur = cur.right;
|
||||
// Target node is in cur's left subtree
|
||||
else if (cur.val > _num)
|
||||
cur = cur.left;
|
||||
// Found target node, exit loop
|
||||
else
|
||||
break;
|
||||
}
|
||||
// Return target node
|
||||
return cur;
|
||||
}
|
||||
|
||||
/* Insert node */
|
||||
void insert(int _num) {
|
||||
// If tree is empty, initialize root node
|
||||
if (_root == null) {
|
||||
_root = TreeNode(_num);
|
||||
return;
|
||||
}
|
||||
TreeNode? cur = _root;
|
||||
TreeNode? pre = null;
|
||||
// Loop search, exit after passing leaf node
|
||||
while (cur != null) {
|
||||
// Found duplicate node, return directly
|
||||
if (cur.val == _num) return;
|
||||
pre = cur;
|
||||
// Insertion position is in cur's right subtree
|
||||
if (cur.val < _num)
|
||||
cur = cur.right;
|
||||
// Insertion position is in cur's left subtree
|
||||
else
|
||||
cur = cur.left;
|
||||
}
|
||||
// Insert node
|
||||
TreeNode? node = TreeNode(_num);
|
||||
if (pre!.val < _num)
|
||||
pre.right = node;
|
||||
else
|
||||
pre.left = node;
|
||||
}
|
||||
|
||||
/* Remove node */
|
||||
void remove(int _num) {
|
||||
// If tree is empty, return directly
|
||||
if (_root == null) return;
|
||||
TreeNode? cur = _root;
|
||||
TreeNode? pre = null;
|
||||
// Loop search, exit after passing leaf node
|
||||
while (cur != null) {
|
||||
// Found node to delete, exit loop
|
||||
if (cur.val == _num) break;
|
||||
pre = cur;
|
||||
// Node to delete is in cur's right subtree
|
||||
if (cur.val < _num)
|
||||
cur = cur.right;
|
||||
// Node to delete is in cur's left subtree
|
||||
else
|
||||
cur = cur.left;
|
||||
}
|
||||
// If no node to delete, return directly
|
||||
if (cur == null) return;
|
||||
// Number of child nodes = 0 or 1
|
||||
if (cur.left == null || cur.right == null) {
|
||||
// When number of child nodes = 0 / 1, child = null / that child node
|
||||
TreeNode? child = cur.left ?? cur.right;
|
||||
// Delete 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
|
||||
_root = child;
|
||||
}
|
||||
} else {
|
||||
// Number of child nodes = 2
|
||||
// Get next node of cur in inorder traversal
|
||||
TreeNode? tmp = cur.right;
|
||||
while (tmp!.left != null) {
|
||||
tmp = tmp.left;
|
||||
}
|
||||
// Recursively delete node tmp
|
||||
remove(tmp.val);
|
||||
// Replace cur with tmp
|
||||
cur.val = tmp.val;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
/* Initialize binary search tree */
|
||||
BinarySearchTree bst = BinarySearchTree();
|
||||
// Please note that different insertion orders will generate different binary trees, this sequence can generate a perfect binary tree
|
||||
List<int> nums = [8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15];
|
||||
for (int _num in nums) {
|
||||
bst.insert(_num);
|
||||
}
|
||||
print("\nInitialized binary tree is\n");
|
||||
printTree(bst.getRoot());
|
||||
|
||||
/* Search node */
|
||||
TreeNode? node = bst.search(7);
|
||||
print("\nFound node object is $node, node value = ${node?.val}");
|
||||
|
||||
/* Insert node */
|
||||
bst.insert(16);
|
||||
print("\nAfter inserting node 16, binary tree is\n");
|
||||
printTree(bst.getRoot());
|
||||
|
||||
/* Remove node */
|
||||
bst.remove(1);
|
||||
print("\nAfter removing node 1, binary tree is\n");
|
||||
printTree(bst.getRoot());
|
||||
bst.remove(2);
|
||||
print("\nAfter removing node 2, binary tree is\n");
|
||||
printTree(bst.getRoot());
|
||||
bst.remove(4);
|
||||
print("\nAfter removing node 4, binary tree is\n");
|
||||
printTree(bst.getRoot());
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* File: binary_tree.dart
|
||||
* Created Time: 2023-04-03
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import '../utils/print_util.dart';
|
||||
import '../utils/tree_node.dart';
|
||||
|
||||
void main() {
|
||||
/* Initialize binary tree */
|
||||
// Initialize node
|
||||
TreeNode n1 = TreeNode(1);
|
||||
TreeNode n2 = TreeNode(2);
|
||||
TreeNode n3 = TreeNode(3);
|
||||
TreeNode n4 = TreeNode(4);
|
||||
TreeNode n5 = TreeNode(5);
|
||||
// Build references (pointers) between nodes
|
||||
n1.left = n2;
|
||||
n1.right = n3;
|
||||
n2.left = n4;
|
||||
n2.right = n5;
|
||||
print("\nInitialize binary tree\n");
|
||||
printTree(n1);
|
||||
|
||||
/* Insert node P between n1 -> n2 */
|
||||
TreeNode p = TreeNode(0);
|
||||
// Insert node p between n1 -> n2
|
||||
n1.left = p;
|
||||
p.left = n2;
|
||||
print("\nAfter inserting node P\n");
|
||||
printTree(n1);
|
||||
// Remove node P
|
||||
n1.left = n2;
|
||||
print("\nAfter removing node P\n");
|
||||
printTree(n1);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* File: binary_tree_bfs.dart
|
||||
* Created Time: 2023-04-03
|
||||
* Author: liuyuxin (gvenusleo@gmai.com)
|
||||
*/
|
||||
|
||||
import 'dart:collection';
|
||||
import '../utils/print_util.dart';
|
||||
import '../utils/tree_node.dart';
|
||||
|
||||
/* Level-order traversal */
|
||||
List<int> levelOrder(TreeNode? root) {
|
||||
// Initialize queue, add root node
|
||||
Queue<TreeNode?> queue = Queue();
|
||||
queue.add(root);
|
||||
// Initialize a list to save the traversal sequence
|
||||
List<int> res = [];
|
||||
while (queue.isNotEmpty) {
|
||||
TreeNode? node = queue.removeFirst(); // Dequeue
|
||||
res.add(node!.val); // Save node value
|
||||
if (node.left != null) queue.add(node.left); // Left child node enqueue
|
||||
if (node.right != null) queue.add(node.right); // Right child node enqueue
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
/* Initialize binary tree */
|
||||
// Here we use a function to generate a binary tree directly from an array
|
||||
TreeNode? root = listToTree([1, 2, 3, 4, 5, 6, 7]);
|
||||
print("\nInitialize binary tree\n");
|
||||
printTree(root);
|
||||
|
||||
// Level-order traversal
|
||||
List<int> res = levelOrder(root);
|
||||
print("\nLevel-order traversal node print sequence = $res");
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* File: binary_tree_dfs.dart
|
||||
* Created Time: 2023-04-04
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
import '../utils/print_util.dart';
|
||||
import '../utils/tree_node.dart';
|
||||
|
||||
// Initialize list for storing traversal sequence
|
||||
List<int> list = [];
|
||||
|
||||
/* Preorder traversal */
|
||||
void preOrder(TreeNode? node) {
|
||||
if (node == null) return;
|
||||
// Visit priority: root node -> left subtree -> right subtree
|
||||
list.add(node.val);
|
||||
preOrder(node.left);
|
||||
preOrder(node.right);
|
||||
}
|
||||
|
||||
/* Inorder traversal */
|
||||
void inOrder(TreeNode? node) {
|
||||
if (node == null) return;
|
||||
// Visit priority: left subtree -> root node -> right subtree
|
||||
inOrder(node.left);
|
||||
list.add(node.val);
|
||||
inOrder(node.right);
|
||||
}
|
||||
|
||||
/* Postorder traversal */
|
||||
void postOrder(TreeNode? node) {
|
||||
if (node == null) return;
|
||||
// Visit priority: left subtree -> right subtree -> root node
|
||||
postOrder(node.left);
|
||||
postOrder(node.right);
|
||||
list.add(node.val);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
void main() {
|
||||
/* Initialize binary tree */
|
||||
// Here we use a function to generate a binary tree directly from an array
|
||||
TreeNode? root = listToTree([1, 2, 3, 4, 5, 6, 7]);
|
||||
print("\nInitialize binary tree\n");
|
||||
printTree(root);
|
||||
|
||||
/* Preorder traversal */
|
||||
list.clear();
|
||||
preOrder(root);
|
||||
print("\nPre-order traversal node print sequence = $list");
|
||||
|
||||
/* Inorder traversal */
|
||||
list.clear();
|
||||
inOrder(root);
|
||||
print("\nIn-order traversal node print sequence = $list");
|
||||
|
||||
/* Postorder traversal */
|
||||
list.clear();
|
||||
postOrder(root);
|
||||
print("\nPost-order traversal node print sequence = $list");
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* File: list_node.dart
|
||||
* Created Time: 2023-01-23
|
||||
* Author: Jefferson (JeffersonHuang77@gmail.com)
|
||||
*/
|
||||
|
||||
/* Linked list node */
|
||||
class ListNode {
|
||||
int val;
|
||||
ListNode? next;
|
||||
|
||||
ListNode(this.val, [this.next]);
|
||||
}
|
||||
|
||||
/* Deserialize a list into a linked list */
|
||||
ListNode? listToLinkedList(List<int> list) {
|
||||
ListNode dum = ListNode(0);
|
||||
ListNode? head = dum;
|
||||
for (int val in list) {
|
||||
head?.next = ListNode(val);
|
||||
head = head?.next;
|
||||
}
|
||||
return dum.next;
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* File: print_util.dart
|
||||
* Created Time: 2023-01-23
|
||||
* Author: Jefferson (JeffersonHuang77@gmail.com)
|
||||
*/
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'list_node.dart';
|
||||
import 'tree_node.dart';
|
||||
|
||||
class Trunk {
|
||||
Trunk? prev;
|
||||
String str;
|
||||
|
||||
Trunk(this.prev, this.str);
|
||||
}
|
||||
|
||||
/* Print matrix (Array) */
|
||||
void printMatrix(List<List<int>> matrix) {
|
||||
print("[");
|
||||
for (List<int> row in matrix) {
|
||||
print(" $row,");
|
||||
}
|
||||
print("]");
|
||||
}
|
||||
|
||||
/* Print linked list */
|
||||
void printLinkedList(ListNode? head) {
|
||||
List<String> list = [];
|
||||
|
||||
while (head != null) {
|
||||
list.add('${head.val}');
|
||||
head = head.next;
|
||||
}
|
||||
|
||||
print(list.join(' -> '));
|
||||
}
|
||||
|
||||
/**
|
||||
* Print binary tree
|
||||
* This tree printer is borrowed from TECHIE DELIGHT
|
||||
* https://www.techiedelight.com/c-program-print-binary-tree/
|
||||
*/
|
||||
void printTree(TreeNode? root, [Trunk? prev = null, bool isRight = false]) {
|
||||
if (root == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
String prev_str = ' ';
|
||||
Trunk trunk = Trunk(prev, prev_str);
|
||||
|
||||
printTree(root.right, trunk, true);
|
||||
|
||||
if (prev == null) {
|
||||
trunk.str = '———';
|
||||
} else if (isRight) {
|
||||
trunk.str = '/———';
|
||||
prev_str = ' |';
|
||||
} else {
|
||||
trunk.str = '\\———';
|
||||
prev.str = prev_str;
|
||||
}
|
||||
showTrunks(trunk);
|
||||
print(' ${root.val}');
|
||||
|
||||
if (prev != null) {
|
||||
prev.str = prev_str;
|
||||
}
|
||||
trunk.str = ' |';
|
||||
|
||||
printTree(root.left, trunk, false);
|
||||
}
|
||||
|
||||
void showTrunks(Trunk? p) {
|
||||
if (p == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
showTrunks(p.prev);
|
||||
stdout.write(p.str);
|
||||
}
|
||||
|
||||
/* Print heap */
|
||||
void printHeap(List<int> heap) {
|
||||
print("Array representation of heap: $heap");
|
||||
print("Heap tree representation:");
|
||||
TreeNode? root = listToTree(heap);
|
||||
printTree(root);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* File: tree_node.dart
|
||||
* Created Time: 2023-2-12
|
||||
* Author: Jefferson (JeffersonHuang77@gmail.com)
|
||||
*/
|
||||
|
||||
/* Binary tree node class */
|
||||
class TreeNode {
|
||||
int val; // Node value
|
||||
int height; // Node height
|
||||
TreeNode? left; // Reference to left child node
|
||||
TreeNode? right; // Reference to right child node
|
||||
|
||||
/* Constructor */
|
||||
TreeNode(this.val, [this.height = 0, this.left, this.right]);
|
||||
}
|
||||
|
||||
/* Deserialize a list into a binary tree: recursion */
|
||||
TreeNode? listToTreeDFS(List<int?> arr, int i) {
|
||||
if (i < 0 || i >= arr.length || arr[i] == null) {
|
||||
return null;
|
||||
}
|
||||
TreeNode? root = TreeNode(arr[i]!);
|
||||
root.left = listToTreeDFS(arr, 2 * i + 1);
|
||||
root.right = listToTreeDFS(arr, 2 * i + 2);
|
||||
return root;
|
||||
}
|
||||
|
||||
/* Deserialize a list into a binary tree */
|
||||
TreeNode? listToTree(List<int?> arr) {
|
||||
return listToTreeDFS(arr, 0);
|
||||
}
|
||||
|
||||
/* Serialize a binary tree into a list: recursion */
|
||||
void treeToListDFS(TreeNode? root, int i, List<int?> res) {
|
||||
if (root == null) return;
|
||||
while (i >= res.length) {
|
||||
res.add(null);
|
||||
}
|
||||
res[i] = root.val;
|
||||
treeToListDFS(root.left, 2 * i + 1, res);
|
||||
treeToListDFS(root.right, 2 * i + 2, res);
|
||||
}
|
||||
|
||||
/* Serialize a binary tree into a list */
|
||||
List<int?> treeToList(TreeNode? root) {
|
||||
List<int?> res = [];
|
||||
treeToListDFS(root, 0, res);
|
||||
return res;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* File: Vertex.dart
|
||||
* Created Time: 2023-05-15
|
||||
* Author: liuyuxin (gvenusleo@gmail.com)
|
||||
*/
|
||||
|
||||
/* Vertex class */
|
||||
class Vertex {
|
||||
int val;
|
||||
Vertex(this.val);
|
||||
|
||||
/* Input value list vals, return vertex list vets */
|
||||
static List<Vertex> valsToVets(List<int> vals) {
|
||||
List<Vertex> vets = [];
|
||||
for (int i in vals) {
|
||||
vets.add(Vertex(i));
|
||||
}
|
||||
return vets;
|
||||
}
|
||||
|
||||
/* Input vertex list vets, return value list vals */
|
||||
static List<int> vetsToVals(List<Vertex> vets) {
|
||||
List<int> vals = [];
|
||||
for (Vertex vet in vets) {
|
||||
vals.add(vet.val);
|
||||
}
|
||||
return vals;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user