mirror of
https://github.com/krahets/hello-algo.git
synced 2026-08-31 04:17:14 +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,79 @@
|
||||
// File: array.go
|
||||
// Created Time: 2022-12-29
|
||||
// Author: GuoWei (gongguowei01@gmail.com), cathay (cathaycchen@gmail.com)
|
||||
|
||||
package chapter_array_and_linkedlist
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
)
|
||||
|
||||
/* Random access to element */
|
||||
func randomAccess(nums []int) (randomNum int) {
|
||||
// Randomly select a number in the interval [0, nums.length)
|
||||
randomIndex := rand.Intn(len(nums))
|
||||
// Retrieve and return the random element
|
||||
randomNum = nums[randomIndex]
|
||||
return
|
||||
}
|
||||
|
||||
/* Extend array length */
|
||||
func extend(nums []int, enlarge int) []int {
|
||||
// Initialize an array with extended length
|
||||
res := make([]int, len(nums)+enlarge)
|
||||
// Copy all elements from the original array to the new array
|
||||
for i, num := range nums {
|
||||
res[i] = num
|
||||
}
|
||||
// Return the extended new array
|
||||
return res
|
||||
}
|
||||
|
||||
/* Insert element num at index index in the array */
|
||||
func insert(nums []int, num int, index int) {
|
||||
// Move all elements at and after index index backward by one position
|
||||
for i := len(nums) - 1; i > index; i-- {
|
||||
nums[i] = nums[i-1]
|
||||
}
|
||||
// Assign num to the element at index index
|
||||
nums[index] = num
|
||||
}
|
||||
|
||||
/* Remove the element at index index */
|
||||
func remove(nums []int, index int) {
|
||||
// Move all elements after index index forward by one position
|
||||
for i := index; i < len(nums)-1; i++ {
|
||||
nums[i] = nums[i+1]
|
||||
}
|
||||
}
|
||||
|
||||
/* Traverse array */
|
||||
func traverse(nums []int) {
|
||||
count := 0
|
||||
// Traverse array by index
|
||||
for i := 0; i < len(nums); i++ {
|
||||
count += nums[i]
|
||||
}
|
||||
count = 0
|
||||
// Direct traversal of array elements
|
||||
for _, num := range nums {
|
||||
count += num
|
||||
}
|
||||
// Traverse simultaneously data index and elements
|
||||
for i, num := range nums {
|
||||
count += nums[i]
|
||||
count += num
|
||||
}
|
||||
}
|
||||
|
||||
/* Find the specified element in the array */
|
||||
func find(nums []int, target int) (index int) {
|
||||
index = -1
|
||||
for i := 0; i < len(nums); i++ {
|
||||
if nums[i] == target {
|
||||
index = i
|
||||
break
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// File: array_test.go
|
||||
// Created Time: 2022-12-29
|
||||
// Author: GuoWei (gongguowei01@gmail.com), cathay (cathaycchen@gmail.com)
|
||||
|
||||
package chapter_array_and_linkedlist
|
||||
|
||||
/**
|
||||
We treat Go Slice as Array here. This reduces
|
||||
the learning cost and allows us to focus on data structures and algorithms.
|
||||
*/
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
/* Driver Code */
|
||||
func TestArray(t *testing.T) {
|
||||
/* Initialize array */
|
||||
var arr [5]int
|
||||
fmt.Println("Array arr =", arr)
|
||||
// In Go, specifying length ([5]int) creates an array, not specifying length ([]int) creates a slice
|
||||
// Since Go arrays are designed to have their length determined at compile time, only constants can be used to specify the length
|
||||
// For convenience in implementing the extend() function, slices are treated as arrays below
|
||||
nums := []int{1, 3, 2, 5, 4}
|
||||
fmt.Println("Array nums =", nums)
|
||||
|
||||
/* Insert element */
|
||||
randomNum := randomAccess(nums)
|
||||
fmt.Println("Get random element in nums", randomNum)
|
||||
|
||||
/* Traverse array */
|
||||
nums = extend(nums, 3)
|
||||
fmt.Println("Extend array length to 8, get nums =", nums)
|
||||
|
||||
/* Insert element */
|
||||
insert(nums, 6, 3)
|
||||
fmt.Println("Insert number 6 at index 3, get nums =", nums)
|
||||
|
||||
/* Remove element */
|
||||
remove(nums, 2)
|
||||
fmt.Println("Remove element at index 2, get nums =", nums)
|
||||
|
||||
/* Traverse array */
|
||||
traverse(nums)
|
||||
|
||||
/* Find element */
|
||||
index := find(nums, 3)
|
||||
fmt.Println("Find element 3 in nums, get index =", index)
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// File: linked_list.go
|
||||
// Created Time: 2022-12-29
|
||||
// Author: cathay (cathaycchen@gmail.com)
|
||||
|
||||
package chapter_array_and_linkedlist
|
||||
|
||||
import (
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
/* Insert node P after node n0 in the linked list */
|
||||
func insertNode(n0 *ListNode, P *ListNode) {
|
||||
n1 := n0.Next
|
||||
P.Next = n1
|
||||
n0.Next = P
|
||||
}
|
||||
|
||||
/* Remove the first node after node n0 in the linked list */
|
||||
func removeItem(n0 *ListNode) {
|
||||
if n0.Next == nil {
|
||||
return
|
||||
}
|
||||
// n0 -> P -> n1
|
||||
P := n0.Next
|
||||
n1 := P.Next
|
||||
n0.Next = n1
|
||||
}
|
||||
|
||||
/* Access the node at index index in the linked list */
|
||||
func access(head *ListNode, index int) *ListNode {
|
||||
for i := 0; i < index; i++ {
|
||||
if head == nil {
|
||||
return nil
|
||||
}
|
||||
head = head.Next
|
||||
}
|
||||
return head
|
||||
}
|
||||
|
||||
/* Find the first node with value target in the linked list */
|
||||
func findNode(head *ListNode, target int) int {
|
||||
index := 0
|
||||
for head != nil {
|
||||
if head.Val == target {
|
||||
return index
|
||||
}
|
||||
head = head.Next
|
||||
index++
|
||||
}
|
||||
return -1
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// File: linked_list_test.go
|
||||
// Created Time: 2022-12-29
|
||||
// Author: cathay (cathaycchen@gmail.com)
|
||||
|
||||
package chapter_array_and_linkedlist
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
func TestLinkedList(t *testing.T) {
|
||||
/* Initialize linked list 1 -> 3 -> 2 -> 5 -> 4 */
|
||||
// Initialize each node
|
||||
n0 := NewListNode(1)
|
||||
n1 := NewListNode(3)
|
||||
n2 := NewListNode(2)
|
||||
n3 := NewListNode(5)
|
||||
n4 := NewListNode(4)
|
||||
|
||||
// Build references between nodes
|
||||
n0.Next = n1
|
||||
n1.Next = n2
|
||||
n2.Next = n3
|
||||
n3.Next = n4
|
||||
fmt.Println("Initialized linked list is")
|
||||
PrintLinkedList(n0)
|
||||
|
||||
/* Insert node */
|
||||
insertNode(n0, NewListNode(0))
|
||||
fmt.Println("Linked list after inserting node is")
|
||||
PrintLinkedList(n0)
|
||||
|
||||
/* Remove node */
|
||||
removeItem(n0)
|
||||
fmt.Println("Linked list after removing node is")
|
||||
PrintLinkedList(n0)
|
||||
|
||||
/* Access node */
|
||||
node := access(n0, 3)
|
||||
fmt.Println("Value of node at index 3 in linked list =", node)
|
||||
|
||||
/* Search node */
|
||||
index := findNode(n0, 2)
|
||||
fmt.Println("Index of node with value 2 in linked list =", index)
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// File: list_test.go
|
||||
// Created Time: 2022-12-18
|
||||
// Author: msk397 (machangxinq@gmail.com)
|
||||
|
||||
package chapter_array_and_linkedlist
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"testing"
|
||||
)
|
||||
|
||||
/* Driver Code */
|
||||
func TestList(t *testing.T) {
|
||||
/* Initialize list */
|
||||
nums := []int{1, 3, 2, 5, 4}
|
||||
fmt.Println("List nums =", nums)
|
||||
|
||||
/* Update element */
|
||||
num := nums[1] // Access element at index 1
|
||||
fmt.Println("Access element at index 1, get num =", num)
|
||||
|
||||
/* Add elements at the end */
|
||||
nums[1] = 0 // Update element at index 1 to 0
|
||||
fmt.Println("Update element at index 1 to 0, get nums =", nums)
|
||||
|
||||
/* Remove element */
|
||||
nums = nil
|
||||
fmt.Println("After clearing list, nums =", nums)
|
||||
|
||||
/* Direct traversal of list elements */
|
||||
nums = append(nums, 1)
|
||||
nums = append(nums, 3)
|
||||
nums = append(nums, 2)
|
||||
nums = append(nums, 5)
|
||||
nums = append(nums, 4)
|
||||
fmt.Println("After adding elements, nums =", nums)
|
||||
|
||||
/* Sort list */
|
||||
nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // Insert number 6 at index 3
|
||||
fmt.Println("Insert number 6 at index 3, get nums =", nums)
|
||||
|
||||
/* Remove element */
|
||||
nums = append(nums[:3], nums[4:]...) // Remove element at index 3
|
||||
fmt.Println("Remove element at index 3, get nums =", nums)
|
||||
|
||||
/* Traverse list by index */
|
||||
count := 0
|
||||
for i := 0; i < len(nums); i++ {
|
||||
count += nums[i]
|
||||
}
|
||||
/* Directly traverse list elements */
|
||||
count = 0
|
||||
for _, x := range nums {
|
||||
count += x
|
||||
}
|
||||
|
||||
/* Concatenate two lists */
|
||||
nums1 := []int{6, 8, 7, 10, 9}
|
||||
nums = append(nums, nums1...) // Concatenate list nums1 to nums
|
||||
fmt.Println("Concatenate list nums1 to nums, get nums =", nums)
|
||||
|
||||
/* Sort list */
|
||||
sort.Ints(nums) // After sorting, list elements are arranged from smallest to largest
|
||||
fmt.Println("After sorting list, nums =", nums)
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// File: my_list.go
|
||||
// Created Time: 2022-12-18
|
||||
// Author: msk397 (machangxinq@gmail.com)
|
||||
|
||||
package chapter_array_and_linkedlist
|
||||
|
||||
/* List class */
|
||||
type myList struct {
|
||||
arrCapacity int
|
||||
arr []int
|
||||
arrSize int
|
||||
extendRatio int
|
||||
}
|
||||
|
||||
/* Constructor */
|
||||
func newMyList() *myList {
|
||||
return &myList{
|
||||
arrCapacity: 10, // List capacity
|
||||
arr: make([]int, 10), // Array (stores list elements)
|
||||
arrSize: 0, // List length (current number of elements)
|
||||
extendRatio: 2, // Multiple by which the list capacity is extended each time
|
||||
}
|
||||
}
|
||||
|
||||
/* Get list length (current number of elements) */
|
||||
func (l *myList) size() int {
|
||||
return l.arrSize
|
||||
}
|
||||
|
||||
/* Get list capacity */
|
||||
func (l *myList) capacity() int {
|
||||
return l.arrCapacity
|
||||
}
|
||||
|
||||
/* Update element */
|
||||
func (l *myList) get(index int) int {
|
||||
// If the index is out of bounds, throw an exception, as below
|
||||
if index < 0 || index >= l.arrSize {
|
||||
panic("Index out of bounds")
|
||||
}
|
||||
return l.arr[index]
|
||||
}
|
||||
|
||||
/* Add elements at the end */
|
||||
func (l *myList) set(num, index int) {
|
||||
if index < 0 || index >= l.arrSize {
|
||||
panic("Index out of bounds")
|
||||
}
|
||||
l.arr[index] = num
|
||||
}
|
||||
|
||||
/* Direct traversal of list elements */
|
||||
func (l *myList) add(num int) {
|
||||
// When the number of elements exceeds capacity, trigger the extension mechanism
|
||||
if l.arrSize == l.arrCapacity {
|
||||
l.extendCapacity()
|
||||
}
|
||||
l.arr[l.arrSize] = num
|
||||
// Update the number of elements
|
||||
l.arrSize++
|
||||
}
|
||||
|
||||
/* Sort list */
|
||||
func (l *myList) insert(num, index int) {
|
||||
if index < 0 || index >= l.arrSize {
|
||||
panic("Index out of bounds")
|
||||
}
|
||||
// When the number of elements exceeds capacity, trigger the extension mechanism
|
||||
if l.arrSize == l.arrCapacity {
|
||||
l.extendCapacity()
|
||||
}
|
||||
// Move all elements after index index forward by one position
|
||||
for j := l.arrSize - 1; j >= index; j-- {
|
||||
l.arr[j+1] = l.arr[j]
|
||||
}
|
||||
l.arr[index] = num
|
||||
// Update the number of elements
|
||||
l.arrSize++
|
||||
}
|
||||
|
||||
/* Remove element */
|
||||
func (l *myList) remove(index int) int {
|
||||
if index < 0 || index >= l.arrSize {
|
||||
panic("Index out of bounds")
|
||||
}
|
||||
num := l.arr[index]
|
||||
// Create a new array with length _extend_ratio times the original array, and copy the original array to the new array
|
||||
for j := index; j < l.arrSize-1; j++ {
|
||||
l.arr[j] = l.arr[j+1]
|
||||
}
|
||||
// Update the number of elements
|
||||
l.arrSize--
|
||||
// Return the removed element
|
||||
return num
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
func (l *myList) extendCapacity() {
|
||||
// Create a new array with length extendRatio times the original array and copy the original array to the new array
|
||||
l.arr = append(l.arr, make([]int, l.arrCapacity*(l.extendRatio-1))...)
|
||||
// Add elements at the end
|
||||
l.arrCapacity = len(l.arr)
|
||||
}
|
||||
|
||||
/* Return list with valid length */
|
||||
func (l *myList) toArray() []int {
|
||||
// Elements enqueue
|
||||
return l.arr[:l.arrSize]
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// File: my_list_test.go
|
||||
// Created Time: 2022-12-18
|
||||
// Author: msk397 (machangxinq@gmail.com)
|
||||
|
||||
package chapter_array_and_linkedlist
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
/* Driver Code */
|
||||
func TestMyList(t *testing.T) {
|
||||
/* Initialize list */
|
||||
nums := newMyList()
|
||||
/* Direct traversal of list elements */
|
||||
nums.add(1)
|
||||
nums.add(3)
|
||||
nums.add(2)
|
||||
nums.add(5)
|
||||
nums.add(4)
|
||||
fmt.Printf("List nums = %v, capacity = %v, length = %v\n", nums.toArray(), nums.capacity(), nums.size())
|
||||
|
||||
/* Sort list */
|
||||
nums.insert(6, 3)
|
||||
fmt.Printf("Insert number 6 at index 3, get nums = %v\n", nums.toArray())
|
||||
|
||||
/* Remove element */
|
||||
nums.remove(3)
|
||||
fmt.Printf("Remove element at index 3, get nums = %v\n", nums.toArray())
|
||||
|
||||
/* Update element */
|
||||
num := nums.get(1)
|
||||
fmt.Printf("Access element at index 1, get num = %v\n", num)
|
||||
|
||||
/* Add elements at the end */
|
||||
nums.set(0, 1)
|
||||
fmt.Printf("Update element at index 1 to 0, get nums = %v\n", nums.toArray())
|
||||
|
||||
/* Test capacity expansion mechanism */
|
||||
for i := 0; i < 10; i++ {
|
||||
// At i = 5, the list length will exceed the list capacity, triggering the expansion mechanism
|
||||
nums.add(i)
|
||||
}
|
||||
fmt.Printf("After expansion, list nums = %v, capacity = %v, length = %v\n", nums.toArray(), nums.capacity(), nums.size())
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// File: n_queens.go
|
||||
// Created Time: 2023-05-09
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
/* Backtracking algorithm: N queens */
|
||||
func backtrack(row, n int, state *[][]string, res *[][][]string, cols, diags1, diags2 *[]bool) {
|
||||
// When all rows are placed, record the solution
|
||||
if row == n {
|
||||
newState := make([][]string, len(*state))
|
||||
for i, _ := range newState {
|
||||
newState[i] = make([]string, len((*state)[0]))
|
||||
copy(newState[i], (*state)[i])
|
||||
|
||||
}
|
||||
*res = append(*res, newState)
|
||||
return
|
||||
}
|
||||
// Traverse all columns
|
||||
for col := 0; col < n; col++ {
|
||||
// Calculate the main diagonal and anti-diagonal corresponding to this cell
|
||||
diag1 := row - col + n - 1
|
||||
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], (*diags1)[diag1], (*diags2)[diag2] = true, true, 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], (*diags1)[diag1], (*diags2)[diag2] = false, false, false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Solve N queens */
|
||||
func nQueens(n int) [][][]string {
|
||||
// Initialize an n*n chessboard, where 'Q' represents a queen and '#' represents an empty cell
|
||||
state := make([][]string, n)
|
||||
for i := 0; i < n; i++ {
|
||||
row := make([]string, n)
|
||||
for i := 0; i < n; i++ {
|
||||
row[i] = "#"
|
||||
}
|
||||
state[i] = row
|
||||
}
|
||||
// Record whether there is a queen in the column
|
||||
cols := make([]bool, n)
|
||||
diags1 := make([]bool, 2*n-1)
|
||||
diags2 := make([]bool, 2*n-1)
|
||||
res := make([][][]string, 0)
|
||||
backtrack(0, n, &state, &res, &cols, &diags1, &diags2)
|
||||
return res
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// File: n_queens_test.go
|
||||
// Created Time: 2023-05-14
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNQueens(t *testing.T) {
|
||||
n := 4
|
||||
res := nQueens(n)
|
||||
|
||||
fmt.Println("Input board size is ", n)
|
||||
fmt.Println("Total queen placement solutions: ", len(res), " solutions")
|
||||
for _, state := range res {
|
||||
fmt.Println("--------------------")
|
||||
for _, row := range state {
|
||||
fmt.Println(row)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// File: permutation_test.go
|
||||
// Created Time: 2023-05-09
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
func TestPermutationI(t *testing.T) {
|
||||
/* Permutations I */
|
||||
nums := []int{1, 2, 3}
|
||||
fmt.Printf("Input array nums = ")
|
||||
PrintSlice(nums)
|
||||
|
||||
res := permutationsI(nums)
|
||||
fmt.Printf("All permutations res = ")
|
||||
fmt.Println(res)
|
||||
}
|
||||
|
||||
func TestPermutationII(t *testing.T) {
|
||||
nums := []int{1, 2, 2}
|
||||
fmt.Printf("Input array nums = ")
|
||||
PrintSlice(nums)
|
||||
|
||||
res := permutationsII(nums)
|
||||
fmt.Printf("All permutations res = ")
|
||||
fmt.Println(res)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// File: permutations_i.go
|
||||
// Created Time: 2023-05-14
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
/* Backtracking algorithm: Permutations I */
|
||||
func backtrackI(state *[]int, choices *[]int, selected *[]bool, res *[][]int) {
|
||||
// When the state length equals the number of elements, record the solution
|
||||
if len(*state) == len(*choices) {
|
||||
newState := append([]int{}, *state...)
|
||||
*res = append(*res, newState)
|
||||
}
|
||||
// Traverse all choices
|
||||
for i := 0; i < len(*choices); i++ {
|
||||
choice := (*choices)[i]
|
||||
// Pruning: do not allow repeated selection of elements
|
||||
if !(*selected)[i] {
|
||||
// Attempt: make choice, update state
|
||||
(*selected)[i] = true
|
||||
*state = append(*state, choice)
|
||||
// Proceed to the next round of selection
|
||||
backtrackI(state, choices, selected, res)
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
(*selected)[i] = false
|
||||
*state = (*state)[:len(*state)-1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Permutations I */
|
||||
func permutationsI(nums []int) [][]int {
|
||||
res := make([][]int, 0)
|
||||
state := make([]int, 0)
|
||||
selected := make([]bool, len(nums))
|
||||
backtrackI(&state, &nums, &selected, &res)
|
||||
return res
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// File: permutations_ii.go
|
||||
// Created Time: 2023-05-14
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
/* Backtracking algorithm: Permutations II */
|
||||
func backtrackII(state *[]int, choices *[]int, selected *[]bool, res *[][]int) {
|
||||
// When the state length equals the number of elements, record the solution
|
||||
if len(*state) == len(*choices) {
|
||||
newState := append([]int{}, *state...)
|
||||
*res = append(*res, newState)
|
||||
}
|
||||
// Traverse all choices
|
||||
duplicated := make(map[int]struct{}, 0)
|
||||
for i := 0; i < len(*choices); i++ {
|
||||
choice := (*choices)[i]
|
||||
// Pruning: do not allow repeated selection of elements and do not allow repeated selection of equal elements
|
||||
if _, ok := duplicated[choice]; !ok && !(*selected)[i] {
|
||||
// Attempt: make choice, update state
|
||||
// Record the selected element value
|
||||
duplicated[choice] = struct{}{}
|
||||
(*selected)[i] = true
|
||||
*state = append(*state, choice)
|
||||
// Proceed to the next round of selection
|
||||
backtrackII(state, choices, selected, res)
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
(*selected)[i] = false
|
||||
*state = (*state)[:len(*state)-1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Permutations II */
|
||||
func permutationsII(nums []int) [][]int {
|
||||
res := make([][]int, 0)
|
||||
state := make([]int, 0)
|
||||
selected := make([]bool, len(nums))
|
||||
backtrackII(&state, &nums, &selected, &res)
|
||||
return res
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// File: preorder_traversal_i_compact.go
|
||||
// Created Time: 2023-05-09
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
import (
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
/* Preorder traversal: Example 1 */
|
||||
func preOrderI(root *TreeNode, res *[]*TreeNode) {
|
||||
if root == nil {
|
||||
return
|
||||
}
|
||||
if (root.Val).(int) == 7 {
|
||||
// Record solution
|
||||
*res = append(*res, root)
|
||||
}
|
||||
preOrderI(root.Left, res)
|
||||
preOrderI(root.Right, res)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// File: preorder_traversal_ii_compact.go
|
||||
// Created Time: 2023-05-09
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
import (
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
/* Preorder traversal: Example 2 */
|
||||
func preOrderII(root *TreeNode, res *[][]*TreeNode, path *[]*TreeNode) {
|
||||
if root == nil {
|
||||
return
|
||||
}
|
||||
// Attempt
|
||||
*path = append(*path, root)
|
||||
if root.Val.(int) == 7 {
|
||||
// Record solution
|
||||
*res = append(*res, append([]*TreeNode{}, *path...))
|
||||
}
|
||||
preOrderII(root.Left, res, path)
|
||||
preOrderII(root.Right, res, path)
|
||||
// Backtrack
|
||||
*path = (*path)[:len(*path)-1]
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// File: preorder_traversal_iii_compact.go
|
||||
// Created Time: 2023-05-09
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
import (
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
/* Preorder traversal: Example 3 */
|
||||
func preOrderIII(root *TreeNode, res *[][]*TreeNode, path *[]*TreeNode) {
|
||||
// Pruning
|
||||
if root == nil || root.Val == 3 {
|
||||
return
|
||||
}
|
||||
// Attempt
|
||||
*path = append(*path, root)
|
||||
if root.Val.(int) == 7 {
|
||||
// Record solution
|
||||
*res = append(*res, append([]*TreeNode{}, *path...))
|
||||
}
|
||||
preOrderIII(root.Left, res, path)
|
||||
preOrderIII(root.Right, res, path)
|
||||
// Backtrack
|
||||
*path = (*path)[:len(*path)-1]
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// File: preorder_traversal_iii_template.go
|
||||
// Created Time: 2023-05-09
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
import (
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
/* Check if the current state is a solution */
|
||||
func isSolution(state *[]*TreeNode) bool {
|
||||
return len(*state) != 0 && (*state)[len(*state)-1].Val == 7
|
||||
}
|
||||
|
||||
/* Record solution */
|
||||
func recordSolution(state *[]*TreeNode, res *[][]*TreeNode) {
|
||||
*res = append(*res, append([]*TreeNode{}, *state...))
|
||||
}
|
||||
|
||||
/* Check if the choice is valid under the current state */
|
||||
func isValid(state *[]*TreeNode, choice *TreeNode) bool {
|
||||
return choice != nil && choice.Val != 3
|
||||
}
|
||||
|
||||
/* Update state */
|
||||
func makeChoice(state *[]*TreeNode, choice *TreeNode) {
|
||||
*state = append(*state, choice)
|
||||
}
|
||||
|
||||
/* Restore state */
|
||||
func undoChoice(state *[]*TreeNode, choice *TreeNode) {
|
||||
*state = (*state)[:len(*state)-1]
|
||||
}
|
||||
|
||||
/* Backtracking algorithm: Example 3 */
|
||||
func backtrackIII(state *[]*TreeNode, choices *[]*TreeNode, res *[][]*TreeNode) {
|
||||
// Check if it is a solution
|
||||
if isSolution(state) {
|
||||
// Record solution
|
||||
recordSolution(state, res)
|
||||
}
|
||||
// Traverse all choices
|
||||
for _, choice := range *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
|
||||
temp := make([]*TreeNode, 0)
|
||||
temp = append(temp, choice.Left, choice.Right)
|
||||
backtrackIII(state, &temp, res)
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
undoChoice(state, choice)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// File: preorder_traversal_i_compact_test.go
|
||||
// Created Time: 2023-05-09
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
func TestPreorderTraversalICompact(t *testing.T) {
|
||||
/* Initialize binary tree */
|
||||
root := SliceToTree([]any{1, 7, 3, 4, 5, 6, 7})
|
||||
fmt.Println("\nInitialize binary tree")
|
||||
PrintTree(root)
|
||||
|
||||
// Preorder traversal
|
||||
res := make([]*TreeNode, 0)
|
||||
preOrderI(root, &res)
|
||||
|
||||
fmt.Println("\nOutput all nodes with value 7")
|
||||
for _, node := range res {
|
||||
fmt.Printf("%v ", node.Val)
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
func TestPreorderTraversalIICompact(t *testing.T) {
|
||||
/* Initialize binary tree */
|
||||
root := SliceToTree([]any{1, 7, 3, 4, 5, 6, 7})
|
||||
fmt.Println("\nInitialize binary tree")
|
||||
PrintTree(root)
|
||||
|
||||
// Preorder traversal
|
||||
path := make([]*TreeNode, 0)
|
||||
res := make([][]*TreeNode, 0)
|
||||
preOrderII(root, &res, &path)
|
||||
|
||||
fmt.Println("\nOutput all paths from root node to node 7")
|
||||
for _, path := range res {
|
||||
for _, node := range path {
|
||||
fmt.Printf("%v ", node.Val)
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreorderTraversalIIICompact(t *testing.T) {
|
||||
/* Initialize binary tree */
|
||||
root := SliceToTree([]any{1, 7, 3, 4, 5, 6, 7})
|
||||
fmt.Println("\nInitialize binary tree")
|
||||
PrintTree(root)
|
||||
|
||||
// Preorder traversal
|
||||
path := make([]*TreeNode, 0)
|
||||
res := make([][]*TreeNode, 0)
|
||||
preOrderIII(root, &res, &path)
|
||||
|
||||
fmt.Println("\nOutput all paths from root node to node 7, paths do not include nodes with value 3")
|
||||
for _, path := range res {
|
||||
for _, node := range path {
|
||||
fmt.Printf("%v ", node.Val)
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreorderTraversalIIITemplate(t *testing.T) {
|
||||
/* Initialize binary tree */
|
||||
root := SliceToTree([]any{1, 7, 3, 4, 5, 6, 7})
|
||||
fmt.Println("\nInitialize binary tree")
|
||||
PrintTree(root)
|
||||
|
||||
// Backtracking algorithm
|
||||
res := make([][]*TreeNode, 0)
|
||||
state := make([]*TreeNode, 0)
|
||||
choices := make([]*TreeNode, 0)
|
||||
choices = append(choices, root)
|
||||
backtrackIII(&state, &choices, &res)
|
||||
|
||||
fmt.Println("\nOutput all paths from root node to node 7, paths do not include nodes with value 3")
|
||||
for _, path := range res {
|
||||
for _, node := range path {
|
||||
fmt.Printf("%v ", node.Val)
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// File: subset_sum_i.go
|
||||
// Created Time: 2023-06-24
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
import "sort"
|
||||
|
||||
/* Backtracking algorithm: Subset sum I */
|
||||
func backtrackSubsetSumI(start, target int, state, choices *[]int, res *[][]int) {
|
||||
// When the subset sum equals target, record the solution
|
||||
if target == 0 {
|
||||
newState := append([]int{}, *state...)
|
||||
*res = append(*res, newState)
|
||||
return
|
||||
}
|
||||
// Traverse all choices
|
||||
// Pruning 2: start traversing from start to avoid generating duplicate subsets
|
||||
for i := start; i < len(*choices); 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 = append(*state, (*choices)[i])
|
||||
// Proceed to the next round of selection
|
||||
backtrackSubsetSumI(i, target-(*choices)[i], state, choices, res)
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
*state = (*state)[:len(*state)-1]
|
||||
}
|
||||
}
|
||||
|
||||
/* Solve subset sum I */
|
||||
func subsetSumI(nums []int, target int) [][]int {
|
||||
state := make([]int, 0) // State (subset)
|
||||
sort.Ints(nums) // Sort nums
|
||||
start := 0 // Start point for traversal
|
||||
res := make([][]int, 0) // Result list (subset list)
|
||||
backtrackSubsetSumI(start, target, &state, &nums, &res)
|
||||
return res
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// File: subset_sum_i_naive.go
|
||||
// Created Time: 2023-06-24
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
/* Backtracking algorithm: Subset sum I */
|
||||
func backtrackSubsetSumINaive(total, target int, state, choices *[]int, res *[][]int) {
|
||||
// When the subset sum equals target, record the solution
|
||||
if target == total {
|
||||
newState := append([]int{}, *state...)
|
||||
*res = append(*res, newState)
|
||||
return
|
||||
}
|
||||
// Traverse all choices
|
||||
for i := 0; i < len(*choices); 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 = append(*state, (*choices)[i])
|
||||
// Proceed to the next round of selection
|
||||
backtrackSubsetSumINaive(total+(*choices)[i], target, state, choices, res)
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
*state = (*state)[:len(*state)-1]
|
||||
}
|
||||
}
|
||||
|
||||
/* Solve subset sum I (including duplicate subsets) */
|
||||
func subsetSumINaive(nums []int, target int) [][]int {
|
||||
state := make([]int, 0) // State (subset)
|
||||
total := 0 // Subset sum
|
||||
res := make([][]int, 0) // Result list (subset list)
|
||||
backtrackSubsetSumINaive(total, target, &state, &nums, &res)
|
||||
return res
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// File: subset_sum_ii.go
|
||||
// Created Time: 2023-06-24
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
import "sort"
|
||||
|
||||
/* Backtracking algorithm: Subset sum II */
|
||||
func backtrackSubsetSumII(start, target int, state, choices *[]int, res *[][]int) {
|
||||
// When the subset sum equals target, record the solution
|
||||
if target == 0 {
|
||||
newState := append([]int{}, *state...)
|
||||
*res = append(*res, newState)
|
||||
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 i := start; i < len(*choices); 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 = append(*state, (*choices)[i])
|
||||
// Proceed to the next round of selection
|
||||
backtrackSubsetSumII(i+1, target-(*choices)[i], state, choices, res)
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
*state = (*state)[:len(*state)-1]
|
||||
}
|
||||
}
|
||||
|
||||
/* Solve subset sum II */
|
||||
func subsetSumII(nums []int, target int) [][]int {
|
||||
state := make([]int, 0) // State (subset)
|
||||
sort.Ints(nums) // Sort nums
|
||||
start := 0 // Start point for traversal
|
||||
res := make([][]int, 0) // Result list (subset list)
|
||||
backtrackSubsetSumII(start, target, &state, &nums, &res)
|
||||
return res
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// File: subset_sum_test.go
|
||||
// Created Time: 2023-06-24
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
func TestSubsetSumINaive(t *testing.T) {
|
||||
nums := []int{3, 4, 5}
|
||||
target := 9
|
||||
res := subsetSumINaive(nums, target)
|
||||
|
||||
fmt.Printf("target = " + strconv.Itoa(target) + ", input array nums = ")
|
||||
PrintSlice(nums)
|
||||
|
||||
fmt.Println("All subsets with sum equal to " + strconv.Itoa(target) + " are res = ")
|
||||
for i := range res {
|
||||
PrintSlice(res[i])
|
||||
}
|
||||
fmt.Println("Please note that this method outputs results containing duplicate sets")
|
||||
}
|
||||
|
||||
func TestSubsetSumI(t *testing.T) {
|
||||
nums := []int{3, 4, 5}
|
||||
target := 9
|
||||
res := subsetSumI(nums, target)
|
||||
|
||||
fmt.Printf("target = " + strconv.Itoa(target) + ", input array nums = ")
|
||||
PrintSlice(nums)
|
||||
|
||||
fmt.Println("All subsets with sum equal to " + strconv.Itoa(target) + " are res = ")
|
||||
for i := range res {
|
||||
PrintSlice(res[i])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubsetSumII(t *testing.T) {
|
||||
nums := []int{4, 4, 5}
|
||||
target := 9
|
||||
res := subsetSumII(nums, target)
|
||||
|
||||
fmt.Printf("target = " + strconv.Itoa(target) + ", input array nums = ")
|
||||
PrintSlice(nums)
|
||||
|
||||
fmt.Println("All subsets with sum equal to " + strconv.Itoa(target) + " are res = ")
|
||||
for i := range res {
|
||||
PrintSlice(res[i])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
// File: iteration.go
|
||||
// Created Time: 2023-08-28
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_computational_complexity
|
||||
|
||||
import "fmt"
|
||||
|
||||
/* for loop */
|
||||
func forLoop(n int) int {
|
||||
res := 0
|
||||
// Sum 1, 2, ..., n-1, n
|
||||
for i := 1; i <= n; i++ {
|
||||
res += i
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
/* while loop */
|
||||
func whileLoop(n int) int {
|
||||
res := 0
|
||||
// Initialize condition variable
|
||||
i := 1
|
||||
// Sum 1, 2, ..., n-1, n
|
||||
for i <= n {
|
||||
res += i
|
||||
// Update condition variable
|
||||
i++
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
/* while loop (two updates) */
|
||||
func whileLoopII(n int) int {
|
||||
res := 0
|
||||
// Initialize condition variable
|
||||
i := 1
|
||||
// Sum 1, 4, 10, ...
|
||||
for i <= n {
|
||||
res += i
|
||||
// Update condition variable
|
||||
i++
|
||||
i *= 2
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
/* Nested for loop */
|
||||
func nestedForLoop(n int) string {
|
||||
res := ""
|
||||
// Loop i = 1, 2, ..., n-1, n
|
||||
for i := 1; i <= n; i++ {
|
||||
for j := 1; j <= n; j++ {
|
||||
// Loop j = 1, 2, ..., n-1, n
|
||||
res += fmt.Sprintf("(%d, %d), ", i, j)
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// File: iteration_test.go
|
||||
// Created Time: 2023-08-28
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_computational_complexity
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
/* Driver Code */
|
||||
func TestIteration(t *testing.T) {
|
||||
n := 5
|
||||
res := forLoop(n)
|
||||
fmt.Println("\nfor loop sum result res = ", res)
|
||||
|
||||
res = whileLoop(n)
|
||||
fmt.Println("\nwhile loop sum result res = ", res)
|
||||
|
||||
res = whileLoopII(n)
|
||||
fmt.Println("\nwhile loop (two updates) sum result res = ", res)
|
||||
|
||||
resStr := nestedForLoop(n)
|
||||
fmt.Println("\nDouble for loop traversal result ", resStr)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// File: recursion.go
|
||||
// Created Time: 2023-08-28
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_computational_complexity
|
||||
|
||||
import "container/list"
|
||||
|
||||
/* Recursion */
|
||||
func recur(n int) int {
|
||||
// Termination condition
|
||||
if n == 1 {
|
||||
return 1
|
||||
}
|
||||
// Recurse: recursive call
|
||||
res := recur(n - 1)
|
||||
// Return: return result
|
||||
return n + res
|
||||
}
|
||||
|
||||
/* Simulate recursion using iteration */
|
||||
func forLoopRecur(n int) int {
|
||||
// Use an explicit stack to simulate the system call stack
|
||||
stack := list.New()
|
||||
res := 0
|
||||
// Recurse: recursive call
|
||||
for i := n; i > 0; i-- {
|
||||
// Simulate "recurse" with "push"
|
||||
stack.PushBack(i)
|
||||
}
|
||||
// Return: return result
|
||||
for stack.Len() != 0 {
|
||||
// Simulate "return" with "pop"
|
||||
res += stack.Back().Value.(int)
|
||||
stack.Remove(stack.Back())
|
||||
}
|
||||
// res = 1+2+3+...+n
|
||||
return res
|
||||
}
|
||||
|
||||
/* Tail recursion */
|
||||
func tailRecur(n int, res int) int {
|
||||
// Termination condition
|
||||
if n == 0 {
|
||||
return res
|
||||
}
|
||||
// Tail recursive call
|
||||
return tailRecur(n-1, res+n)
|
||||
}
|
||||
|
||||
/* Fibonacci sequence: recursion */
|
||||
func fib(n int) int {
|
||||
// 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)
|
||||
res := fib(n-1) + fib(n-2)
|
||||
// Return result f(n)
|
||||
return res
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// File: recursion_test.go
|
||||
// Created Time: 2023-08-28
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_computational_complexity
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
/* Driver Code */
|
||||
func TestRecursion(t *testing.T) {
|
||||
n := 5
|
||||
res := recur(n)
|
||||
fmt.Println("\nRecursive function sum result res = ", res)
|
||||
|
||||
res = forLoopRecur(n)
|
||||
fmt.Println("\nUsing iteration to simulate recursive sum result res = ", res)
|
||||
|
||||
res = tailRecur(n, 0)
|
||||
fmt.Println("\nTail recursive function sum result res = ", res)
|
||||
|
||||
res = fib(n)
|
||||
fmt.Println("\nThe ", n, "th term of Fibonacci sequence is", res)
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
// File: space_complexity.go
|
||||
// Created Time: 2022-12-15
|
||||
// Author: cathay (cathaycchen@gmail.com)
|
||||
|
||||
package chapter_computational_complexity
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
/* Struct */
|
||||
type node struct {
|
||||
val int
|
||||
next *node
|
||||
}
|
||||
|
||||
/* Create node struct */
|
||||
func newNode(val int) *node {
|
||||
return &node{val: val}
|
||||
}
|
||||
|
||||
/* Function */
|
||||
func function() int {
|
||||
// Perform some operations...
|
||||
return 0
|
||||
}
|
||||
|
||||
/* Constant order */
|
||||
func spaceConstant(n int) {
|
||||
// Constants, variables, objects occupy O(1) space
|
||||
const a = 0
|
||||
b := 0
|
||||
nums := make([]int, 10000)
|
||||
node := newNode(0)
|
||||
// Variables in the loop occupy O(1) space
|
||||
var c int
|
||||
for i := 0; i < n; i++ {
|
||||
c = 0
|
||||
}
|
||||
// Functions in the loop occupy O(1) space
|
||||
for i := 0; i < n; i++ {
|
||||
function()
|
||||
}
|
||||
b += 0
|
||||
c += 0
|
||||
nums[0] = 0
|
||||
node.val = 0
|
||||
}
|
||||
|
||||
/* Linear order */
|
||||
func spaceLinear(n int) {
|
||||
// Array of length n uses O(n) space
|
||||
_ = make([]int, n)
|
||||
// A list of length n occupies O(n) space
|
||||
var nodes []*node
|
||||
for i := 0; i < n; i++ {
|
||||
nodes = append(nodes, newNode(i))
|
||||
}
|
||||
// A hash table of length n occupies O(n) space
|
||||
m := make(map[int]string, n)
|
||||
for i := 0; i < n; i++ {
|
||||
m[i] = strconv.Itoa(i)
|
||||
}
|
||||
}
|
||||
|
||||
/* Linear order (recursive implementation) */
|
||||
func spaceLinearRecur(n int) {
|
||||
fmt.Println("Recursion n =", n)
|
||||
if n == 1 {
|
||||
return
|
||||
}
|
||||
spaceLinearRecur(n - 1)
|
||||
}
|
||||
|
||||
/* Exponential order */
|
||||
func spaceQuadratic(n int) {
|
||||
// Matrix uses O(n^2) space
|
||||
numMatrix := make([][]int, n)
|
||||
for i := 0; i < n; i++ {
|
||||
numMatrix[i] = make([]int, n)
|
||||
}
|
||||
}
|
||||
|
||||
/* Quadratic order (recursive implementation) */
|
||||
func spaceQuadraticRecur(n int) int {
|
||||
if n <= 0 {
|
||||
return 0
|
||||
}
|
||||
nums := make([]int, n)
|
||||
fmt.Printf("In recursion n = %d, nums length = %d \n", n, len(nums))
|
||||
return spaceQuadraticRecur(n - 1)
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
func buildTree(n int) *TreeNode {
|
||||
if n == 0 {
|
||||
return nil
|
||||
}
|
||||
root := NewTreeNode(0)
|
||||
root.Left = buildTree(n - 1)
|
||||
root.Right = buildTree(n - 1)
|
||||
return root
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// File: space_complexity_test.go
|
||||
// Created Time: 2022-12-15
|
||||
// Author: cathay (cathaycchen@gmail.com)
|
||||
|
||||
package chapter_computational_complexity
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
func TestSpaceComplexity(t *testing.T) {
|
||||
n := 5
|
||||
// Constant order
|
||||
spaceConstant(n)
|
||||
// Linear order
|
||||
spaceLinear(n)
|
||||
spaceLinearRecur(n)
|
||||
// Exponential order
|
||||
spaceQuadratic(n)
|
||||
spaceQuadraticRecur(n)
|
||||
// Exponential order
|
||||
root := buildTree(n)
|
||||
PrintTree(root)
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
// File: time_complexity.go
|
||||
// Created Time: 2022-12-13
|
||||
// Author: msk397 (machangxinq@gmail.com)
|
||||
|
||||
package chapter_computational_complexity
|
||||
|
||||
/* Constant order */
|
||||
func constant(n int) int {
|
||||
count := 0
|
||||
size := 100000
|
||||
for i := 0; i < size; i++ {
|
||||
count++
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
/* Linear order */
|
||||
func linear(n int) int {
|
||||
count := 0
|
||||
for i := 0; i < n; i++ {
|
||||
count++
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
/* Linear order (traversing array) */
|
||||
func arrayTraversal(nums []int) int {
|
||||
count := 0
|
||||
// Number of iterations is proportional to the array length
|
||||
for range nums {
|
||||
count++
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
/* Exponential order */
|
||||
func quadratic(n int) int {
|
||||
count := 0
|
||||
// Number of iterations is quadratically related to the data size n
|
||||
for i := 0; i < n; i++ {
|
||||
for j := 0; j < n; j++ {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
/* Quadratic order (bubble sort) */
|
||||
func bubbleSort(nums []int) int {
|
||||
count := 0 // Counter
|
||||
// Outer loop: unsorted range is [0, i]
|
||||
for i := len(nums) - 1; i > 0; i-- {
|
||||
// Inner loop: swap the largest element in the unsorted range [0, i] to the rightmost end of that range
|
||||
for j := 0; j < i; j++ {
|
||||
if nums[j] > nums[j+1] {
|
||||
// Swap nums[j] and nums[j + 1]
|
||||
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) */
|
||||
func exponential(n int) int {
|
||||
count, base := 0, 1
|
||||
// Cells divide into two every round, forming sequence 1, 2, 4, 8, ..., 2^(n-1)
|
||||
for i := 0; i < n; i++ {
|
||||
for 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) */
|
||||
func expRecur(n int) int {
|
||||
if n == 1 {
|
||||
return 1
|
||||
}
|
||||
return expRecur(n-1) + expRecur(n-1) + 1
|
||||
}
|
||||
|
||||
/* Logarithmic order (loop implementation) */
|
||||
func logarithmic(n int) int {
|
||||
count := 0
|
||||
for n > 1 {
|
||||
n = n / 2
|
||||
count++
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
/* Logarithmic order (recursive implementation) */
|
||||
func logRecur(n int) int {
|
||||
if n <= 1 {
|
||||
return 0
|
||||
}
|
||||
return logRecur(n/2) + 1
|
||||
}
|
||||
|
||||
/* Linearithmic order */
|
||||
func linearLogRecur(n int) int {
|
||||
if n <= 1 {
|
||||
return 1
|
||||
}
|
||||
count := linearLogRecur(n/2) + linearLogRecur(n/2)
|
||||
for i := 0; i < n; i++ {
|
||||
count++
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
/* Factorial order (recursive implementation) */
|
||||
func factorialRecur(n int) int {
|
||||
if n == 0 {
|
||||
return 1
|
||||
}
|
||||
count := 0
|
||||
// Split from 1 into n
|
||||
for i := 0; i < n; i++ {
|
||||
count += factorialRecur(n - 1)
|
||||
}
|
||||
return count
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// File: time_complexity_test.go
|
||||
// Created Time: 2022-12-13
|
||||
// Author: msk397 (machangxinq@gmail.com)
|
||||
|
||||
package chapter_computational_complexity
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTimeComplexity(t *testing.T) {
|
||||
n := 8
|
||||
fmt.Println("Input data size n =", n)
|
||||
|
||||
count := constant(n)
|
||||
fmt.Println("Number of constant-order operations =", count)
|
||||
|
||||
count = linear(n)
|
||||
fmt.Println("Number of linear-order operations =", count)
|
||||
count = arrayTraversal(make([]int, n))
|
||||
fmt.Println("Number of linear-order (array traversal) operations =", count)
|
||||
|
||||
count = quadratic(n)
|
||||
fmt.Println("Number of quadratic-order operations =", count)
|
||||
nums := make([]int, n)
|
||||
for i := 0; i < n; i++ {
|
||||
nums[i] = n - i
|
||||
}
|
||||
count = bubbleSort(nums)
|
||||
fmt.Println("Number of quadratic-order (bubble sort) operations =", count)
|
||||
|
||||
count = exponential(n)
|
||||
fmt.Println("Number of exponential-order (loop implementation) operations =", count)
|
||||
count = expRecur(n)
|
||||
fmt.Println("Number of exponential-order (recursive implementation) operations =", count)
|
||||
|
||||
count = logarithmic(n)
|
||||
fmt.Println("Number of logarithmic-order (loop implementation) operations =", count)
|
||||
count = logRecur(n)
|
||||
fmt.Println("Number of logarithmic-order (recursive implementation) operations =", count)
|
||||
|
||||
count = linearLogRecur(n)
|
||||
fmt.Println("Number of linearithmic-order (recursive implementation) operations =", count)
|
||||
|
||||
count = factorialRecur(n)
|
||||
fmt.Println("Number of factorial-order (recursive implementation) operations =", count)
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// File: worst_best_time_complexity.go
|
||||
// Created Time: 2022-12-13
|
||||
// Author: msk397 (machangxinq@gmail.com), cathay (cathaycchen@gmail.com)
|
||||
|
||||
package chapter_computational_complexity
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
)
|
||||
|
||||
/* Generate an array with elements { 1, 2, ..., n }, order shuffled */
|
||||
func randomNumbers(n int) []int {
|
||||
nums := make([]int, n)
|
||||
// Generate array nums = { 1, 2, 3, ..., n }
|
||||
for i := 0; i < n; i++ {
|
||||
nums[i] = i + 1
|
||||
}
|
||||
// Randomly shuffle array elements
|
||||
rand.Shuffle(len(nums), func(i, j int) {
|
||||
nums[i], nums[j] = nums[j], nums[i]
|
||||
})
|
||||
return nums
|
||||
}
|
||||
|
||||
/* Find the index of number 1 in array nums */
|
||||
func findOne(nums []int) int {
|
||||
for i := 0; i < len(nums); 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
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// File: worst_best_time_complexity_test.go
|
||||
// Created Time: 2022-12-13
|
||||
// Author: msk397 (machangxinq@gmail.com), cathay (cathaycchen@gmail.com)
|
||||
|
||||
package chapter_computational_complexity
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWorstBestTimeComplexity(t *testing.T) {
|
||||
for i := 0; i < 10; i++ {
|
||||
n := 100
|
||||
nums := randomNumbers(n)
|
||||
index := findOne(nums)
|
||||
fmt.Println("\nAfter shuffling array [ 1, 2, ..., n ] =", nums)
|
||||
fmt.Println("Index of number 1 is", index)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// File: binary_search_recur.go
|
||||
// Created Time: 2023-07-19
|
||||
// Author: hongyun-robot (1836017030@qq.com)
|
||||
|
||||
package chapter_divide_and_conquer
|
||||
|
||||
/* Binary search: problem f(i, j) */
|
||||
func dfs(nums []int, target, i, j int) int {
|
||||
// If interval is empty, indicating no target element, return -1
|
||||
if i > j {
|
||||
return -1
|
||||
}
|
||||
// Calculate midpoint index
|
||||
m := i + ((j - i) >> 1)
|
||||
// Compare midpoint with target element
|
||||
if nums[m] < target {
|
||||
// If smaller, recurse on right half of array
|
||||
// Recursion subproblem f(m+1, j)
|
||||
return dfs(nums, target, m+1, j)
|
||||
} else if nums[m] > target {
|
||||
// If larger, recurse on left half of array
|
||||
// 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 */
|
||||
func binarySearch(nums []int, target int) int {
|
||||
n := len(nums)
|
||||
return dfs(nums, target, 0, n-1)
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// File: binary_search_recur_test.go
|
||||
// Created Time: 2023-07-19
|
||||
// Author: hongyun-robot (1836017030@qq.com)
|
||||
|
||||
package chapter_divide_and_conquer
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBinarySearch(t *testing.T) {
|
||||
nums := []int{1, 3, 6, 8, 12, 15, 23, 26, 31, 35}
|
||||
target := 6
|
||||
noTarget := 99
|
||||
targetIndex := binarySearch(nums, target)
|
||||
fmt.Println("Index of target element 6 = ", targetIndex)
|
||||
noTargetIndex := binarySearch(nums, noTarget)
|
||||
fmt.Println("Index of non-existent target element = ", noTargetIndex)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// File: build_tree.go
|
||||
// Created Time: 2023-07-20
|
||||
// Author: hongyun-robot (1836017030@qq.com)
|
||||
|
||||
package chapter_divide_and_conquer
|
||||
|
||||
import . "github.com/krahets/hello-algo/pkg"
|
||||
|
||||
/* Build binary tree: divide and conquer */
|
||||
func dfsBuildTree(preorder []int, inorderMap map[int]int, i, l, r int) *TreeNode {
|
||||
// Terminate when the subtree interval is empty
|
||||
if r-l < 0 {
|
||||
return nil
|
||||
}
|
||||
// Initialize the root node
|
||||
root := NewTreeNode(preorder[i])
|
||||
// Query m to divide the left and right subtrees
|
||||
m := inorderMap[preorder[i]]
|
||||
// Subproblem: build the left subtree
|
||||
root.Left = dfsBuildTree(preorder, inorderMap, i+1, l, m-1)
|
||||
// Subproblem: build the right subtree
|
||||
root.Right = dfsBuildTree(preorder, inorderMap, i+1+m-l, m+1, r)
|
||||
// Return the root node
|
||||
return root
|
||||
}
|
||||
|
||||
/* Build binary tree */
|
||||
func buildTree(preorder, inorder []int) *TreeNode {
|
||||
// Initialize hash map, storing the mapping from inorder elements to indices
|
||||
inorderMap := make(map[int]int, len(inorder))
|
||||
for i := 0; i < len(inorder); i++ {
|
||||
inorderMap[inorder[i]] = i
|
||||
}
|
||||
|
||||
root := dfsBuildTree(preorder, inorderMap, 0, 0, len(inorder)-1)
|
||||
return root
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// File: build_tree_test.go
|
||||
// Created Time: 2023-07-20
|
||||
// Author: hongyun-robot (1836017030@qq.com)
|
||||
|
||||
package chapter_divide_and_conquer
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
func TestBuildTree(t *testing.T) {
|
||||
preorder := []int{3, 9, 2, 1, 7}
|
||||
inorder := []int{9, 3, 1, 2, 7}
|
||||
fmt.Print("Preorder traversal = ")
|
||||
PrintSlice(preorder)
|
||||
fmt.Print("Inorder traversal = ")
|
||||
PrintSlice(inorder)
|
||||
|
||||
root := buildTree(preorder, inorder)
|
||||
fmt.Println("The constructed binary tree is:")
|
||||
PrintTree(root)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// File: hanota.go
|
||||
// Created Time: 2023-07-21
|
||||
// Author: hongyun-robot (1836017030@qq.com)
|
||||
|
||||
package chapter_divide_and_conquer
|
||||
|
||||
import "container/list"
|
||||
|
||||
/* Move a disk */
|
||||
func move(src, tar *list.List) {
|
||||
// Take out a disk from the top of src
|
||||
pan := src.Back()
|
||||
// Place the disk on top of tar
|
||||
tar.PushBack(pan.Value)
|
||||
// Remove top disk from src
|
||||
src.Remove(pan)
|
||||
}
|
||||
|
||||
/* Solve the Tower of Hanoi problem f(i) */
|
||||
func dfsHanota(i int, src, buf, tar *list.List) {
|
||||
// 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
|
||||
dfsHanota(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
|
||||
dfsHanota(i-1, buf, src, tar)
|
||||
}
|
||||
|
||||
/* Solve the Tower of Hanoi problem */
|
||||
func solveHanota(A, B, C *list.List) {
|
||||
n := A.Len()
|
||||
// Move the top n disks from A to C using B
|
||||
dfsHanota(n, A, B, C)
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// File: hanota_test.go
|
||||
// Created Time: 2023-07-21
|
||||
// Author: hongyun-robot (1836017030@qq.com)
|
||||
|
||||
package chapter_divide_and_conquer
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
func TestHanota(t *testing.T) {
|
||||
// The tail of the list is the top of the rod
|
||||
A := list.New()
|
||||
for i := 5; i > 0; i-- {
|
||||
A.PushBack(i)
|
||||
}
|
||||
B := list.New()
|
||||
C := list.New()
|
||||
fmt.Println("In initial state:")
|
||||
fmt.Print("A = ")
|
||||
PrintList(A)
|
||||
fmt.Print("B = ")
|
||||
PrintList(B)
|
||||
fmt.Print("C = ")
|
||||
PrintList(C)
|
||||
|
||||
solveHanota(A, B, C)
|
||||
|
||||
fmt.Println("After disk movement is complete:")
|
||||
fmt.Print("A = ")
|
||||
PrintList(A)
|
||||
fmt.Print("B = ")
|
||||
PrintList(B)
|
||||
fmt.Print("C = ")
|
||||
PrintList(C)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// File: climbing_stairs_backtrack.go
|
||||
// Created Time: 2023-07-18
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_dynamic_programming
|
||||
|
||||
/* Backtracking */
|
||||
func backtrack(choices []int, state, n int, res []int) {
|
||||
// When climbing to the n-th stair, add 1 to the solution count
|
||||
if state == n {
|
||||
res[0] = res[0] + 1
|
||||
}
|
||||
// Traverse all choices
|
||||
for _, choice := range 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 */
|
||||
func climbingStairsBacktrack(n int) int {
|
||||
// Can choose to climb up 1 or 2 stairs
|
||||
choices := []int{1, 2}
|
||||
// Start climbing from the 0-th stair
|
||||
state := 0
|
||||
res := make([]int, 1)
|
||||
// Use res[0] to record the solution count
|
||||
res[0] = 0
|
||||
backtrack(choices, state, n, res)
|
||||
return res[0]
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// File: climbing_stairs_constraint_dp.go
|
||||
// Created Time: 2023-07-18
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_dynamic_programming
|
||||
|
||||
/* Climbing stairs with constraint: Dynamic programming */
|
||||
func climbingStairsConstraintDP(n int) int {
|
||||
if n == 1 || n == 2 {
|
||||
return 1
|
||||
}
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
dp := make([][3]int, n+1)
|
||||
// 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 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]
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// File: climbing_stairs_dfs.go
|
||||
// Created Time: 2023-07-18
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_dynamic_programming
|
||||
|
||||
/* Search */
|
||||
func dfs(i int) int {
|
||||
// Known dp[1] and dp[2], return them
|
||||
if i == 1 || i == 2 {
|
||||
return i
|
||||
}
|
||||
// dp[i] = dp[i-1] + dp[i-2]
|
||||
count := dfs(i-1) + dfs(i-2)
|
||||
return count
|
||||
}
|
||||
|
||||
/* Climbing stairs: Search */
|
||||
func climbingStairsDFS(n int) int {
|
||||
return dfs(n)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// File: climbing_stairs_dfs_mem.go
|
||||
// Created Time: 2023-07-18
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_dynamic_programming
|
||||
|
||||
/* Memoization search */
|
||||
func dfsMem(i int, mem []int) int {
|
||||
// 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]
|
||||
count := dfsMem(i-1, mem) + dfsMem(i-2, mem)
|
||||
// Record dp[i]
|
||||
mem[i] = count
|
||||
return count
|
||||
}
|
||||
|
||||
/* Climbing stairs: Memoization search */
|
||||
func climbingStairsDFSMem(n int) int {
|
||||
// mem[i] records the total number of solutions to climb to the i-th stair, -1 means no record
|
||||
mem := make([]int, n+1)
|
||||
for i := range mem {
|
||||
mem[i] = -1
|
||||
}
|
||||
return dfsMem(n, mem)
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// File: climbing_stairs_dp.go
|
||||
// Created Time: 2023-07-18
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_dynamic_programming
|
||||
|
||||
/* Climbing stairs: Dynamic programming */
|
||||
func climbingStairsDP(n int) int {
|
||||
if n == 1 || n == 2 {
|
||||
return n
|
||||
}
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
dp := make([]int, n+1)
|
||||
// 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 i := 3; i <= n; i++ {
|
||||
dp[i] = dp[i-1] + dp[i-2]
|
||||
}
|
||||
return dp[n]
|
||||
}
|
||||
|
||||
/* Climbing stairs: Space-optimized dynamic programming */
|
||||
func climbingStairsDPComp(n int) int {
|
||||
if n == 1 || n == 2 {
|
||||
return n
|
||||
}
|
||||
a, b := 1, 2
|
||||
// State transition: gradually solve larger subproblems from smaller ones
|
||||
for i := 3; i <= n; i++ {
|
||||
a, b = b, a+b
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// File: climbing_stairs_test.go
|
||||
// Created Time: 2023-07-18
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_dynamic_programming
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestClimbingStairsBacktrack(t *testing.T) {
|
||||
n := 9
|
||||
res := climbingStairsBacktrack(n)
|
||||
fmt.Printf("Climbing %d stairs has %d solutions\n", n, res)
|
||||
}
|
||||
|
||||
func TestClimbingStairsDFS(t *testing.T) {
|
||||
n := 9
|
||||
res := climbingStairsDFS(n)
|
||||
fmt.Printf("Climbing %d stairs has %d solutions\n", n, res)
|
||||
}
|
||||
|
||||
func TestClimbingStairsDFSMem(t *testing.T) {
|
||||
n := 9
|
||||
res := climbingStairsDFSMem(n)
|
||||
fmt.Printf("Climbing %d stairs has %d solutions\n", n, res)
|
||||
}
|
||||
|
||||
func TestClimbingStairsDP(t *testing.T) {
|
||||
n := 9
|
||||
res := climbingStairsDP(n)
|
||||
fmt.Printf("Climbing %d stairs has %d solutions\n", n, res)
|
||||
}
|
||||
|
||||
func TestClimbingStairsDPComp(t *testing.T) {
|
||||
n := 9
|
||||
res := climbingStairsDPComp(n)
|
||||
fmt.Printf("Climbing %d stairs has %d solutions\n", n, res)
|
||||
}
|
||||
|
||||
func TestClimbingStairsConstraintDP(t *testing.T) {
|
||||
n := 9
|
||||
res := climbingStairsConstraintDP(n)
|
||||
fmt.Printf("Climbing %d stairs has %d solutions\n", n, res)
|
||||
}
|
||||
|
||||
func TestMinCostClimbingStairsDPComp(t *testing.T) {
|
||||
cost := []int{0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1}
|
||||
fmt.Printf("Input stair cost list is %v\n", cost)
|
||||
|
||||
res := minCostClimbingStairsDP(cost)
|
||||
fmt.Printf("Minimum cost to climb stairs is %d\n", res)
|
||||
|
||||
res = minCostClimbingStairsDPComp(cost)
|
||||
fmt.Printf("Minimum cost to climb stairs is %d\n", res)
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// File: coin_change.go
|
||||
// Created Time: 2023-07-23
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_dynamic_programming
|
||||
|
||||
import "math"
|
||||
|
||||
/* Coin change: Dynamic programming */
|
||||
func coinChangeDP(coins []int, amt int) int {
|
||||
n := len(coins)
|
||||
max := amt + 1
|
||||
// Initialize dp table
|
||||
dp := make([][]int, n+1)
|
||||
for i := 0; i <= n; i++ {
|
||||
dp[i] = make([]int, amt+1)
|
||||
}
|
||||
// State transition: first row and first column
|
||||
for a := 1; a <= amt; a++ {
|
||||
dp[0][a] = max
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
for i := 1; i <= n; i++ {
|
||||
for 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] = int(math.Min(float64(dp[i-1][a]), float64(dp[i][a-coins[i-1]]+1)))
|
||||
}
|
||||
}
|
||||
}
|
||||
if dp[n][amt] != max {
|
||||
return dp[n][amt]
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
/* Coin change: Dynamic programming */
|
||||
func coinChangeDPComp(coins []int, amt int) int {
|
||||
n := len(coins)
|
||||
max := amt + 1
|
||||
// Initialize dp table
|
||||
dp := make([]int, amt+1)
|
||||
for i := 1; i <= amt; i++ {
|
||||
dp[i] = max
|
||||
}
|
||||
// State transition
|
||||
for i := 1; i <= n; i++ {
|
||||
// Traverse in forward order
|
||||
for 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] = int(math.Min(float64(dp[a]), float64(dp[a-coins[i-1]]+1)))
|
||||
}
|
||||
}
|
||||
}
|
||||
if dp[amt] != max {
|
||||
return dp[amt]
|
||||
}
|
||||
return -1
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// File: coin_change_ii.go
|
||||
// Created Time: 2023-07-23
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_dynamic_programming
|
||||
|
||||
/* Coin change II: Dynamic programming */
|
||||
func coinChangeIIDP(coins []int, amt int) int {
|
||||
n := len(coins)
|
||||
// Initialize dp table
|
||||
dp := make([][]int, n+1)
|
||||
for i := 0; i <= n; i++ {
|
||||
dp[i] = make([]int, amt+1)
|
||||
}
|
||||
// Initialize first column
|
||||
for i := 0; i <= n; i++ {
|
||||
dp[i][0] = 1
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
for i := 1; i <= n; i++ {
|
||||
for 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 */
|
||||
func coinChangeIIDPComp(coins []int, amt int) int {
|
||||
n := len(coins)
|
||||
// Initialize dp table
|
||||
dp := make([]int, amt+1)
|
||||
dp[0] = 1
|
||||
// State transition
|
||||
for i := 1; i <= n; i++ {
|
||||
// Traverse in forward order
|
||||
for 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]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// File: coin_change_test.go
|
||||
// Created Time: 2023-07-23
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_dynamic_programming
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCoinChange(t *testing.T) {
|
||||
coins := []int{1, 2, 5}
|
||||
amt := 4
|
||||
|
||||
// Dynamic programming
|
||||
res := coinChangeDP(coins, amt)
|
||||
fmt.Printf("Minimum number of coins needed to make target amount is %d\n", res)
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = coinChangeDPComp(coins, amt)
|
||||
fmt.Printf("Minimum number of coins needed to make target amount is %d\n", res)
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
// File: edit_distance.go
|
||||
// Created Time: 2023-07-23
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_dynamic_programming
|
||||
|
||||
/* Edit distance: Brute-force search */
|
||||
func editDistanceDFS(s string, t string, i int, j int) int {
|
||||
// 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
|
||||
insert := editDistanceDFS(s, t, i, j-1)
|
||||
deleted := editDistanceDFS(s, t, i-1, j)
|
||||
replace := editDistanceDFS(s, t, i-1, j-1)
|
||||
// Return minimum edit steps
|
||||
return MinInt(MinInt(insert, deleted), replace) + 1
|
||||
}
|
||||
|
||||
/* Edit distance: Memoization search */
|
||||
func editDistanceDFSMem(s string, t string, mem [][]int, i int, j int) int {
|
||||
// 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
|
||||
insert := editDistanceDFSMem(s, t, mem, i, j-1)
|
||||
deleted := editDistanceDFSMem(s, t, mem, i-1, j)
|
||||
replace := editDistanceDFSMem(s, t, mem, i-1, j-1)
|
||||
// Record and return minimum edit steps
|
||||
mem[i][j] = MinInt(MinInt(insert, deleted), replace) + 1
|
||||
return mem[i][j]
|
||||
}
|
||||
|
||||
/* Edit distance: Dynamic programming */
|
||||
func editDistanceDP(s string, t string) int {
|
||||
n := len(s)
|
||||
m := len(t)
|
||||
dp := make([][]int, n+1)
|
||||
for i := 0; i <= n; i++ {
|
||||
dp[i] = make([]int, m+1)
|
||||
}
|
||||
// State transition: first row and first column
|
||||
for i := 1; i <= n; i++ {
|
||||
dp[i][0] = i
|
||||
}
|
||||
for j := 1; j <= m; j++ {
|
||||
dp[0][j] = j
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
for i := 1; i <= n; i++ {
|
||||
for 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] = MinInt(MinInt(dp[i][j-1], dp[i-1][j]), dp[i-1][j-1]) + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][m]
|
||||
}
|
||||
|
||||
/* Edit distance: Space-optimized dynamic programming */
|
||||
func editDistanceDPComp(s string, t string) int {
|
||||
n := len(s)
|
||||
m := len(t)
|
||||
dp := make([]int, m+1)
|
||||
// State transition: first row
|
||||
for j := 1; j <= m; j++ {
|
||||
dp[j] = j
|
||||
}
|
||||
// State transition: rest of the rows
|
||||
for i := 1; i <= n; i++ {
|
||||
// State transition: first column
|
||||
leftUp := dp[0] // Temporarily store dp[i-1, j-1]
|
||||
dp[0] = i
|
||||
// State transition: rest of the columns
|
||||
for j := 1; j <= m; j++ {
|
||||
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] = MinInt(MinInt(dp[j-1], dp[j]), leftUp) + 1
|
||||
}
|
||||
leftUp = temp // Update for next round's dp[i-1, j-1]
|
||||
}
|
||||
}
|
||||
return dp[m]
|
||||
}
|
||||
|
||||
func MinInt(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// File: edit_distance_test.go
|
||||
// Created Time: 2023-07-23
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_dynamic_programming
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEditDistanceDFS(test *testing.T) {
|
||||
s := "bag"
|
||||
t := "pack"
|
||||
n := len(s)
|
||||
m := len(t)
|
||||
|
||||
// Brute-force search
|
||||
res := editDistanceDFS(s, t, n, m)
|
||||
fmt.Printf("Changing %s to %s requires a minimum of %d edits\n", s, t, res)
|
||||
|
||||
// Memoization search
|
||||
mem := make([][]int, n+1)
|
||||
for i := 0; i <= n; i++ {
|
||||
mem[i] = make([]int, m+1)
|
||||
for j := 0; j <= m; j++ {
|
||||
mem[i][j] = -1
|
||||
}
|
||||
}
|
||||
res = editDistanceDFSMem(s, t, mem, n, m)
|
||||
fmt.Printf("Changing %s to %s requires a minimum of %d edits\n", s, t, res)
|
||||
|
||||
// Dynamic programming
|
||||
res = editDistanceDP(s, t)
|
||||
fmt.Printf("Changing %s to %s requires a minimum of %d edits\n", s, t, res)
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = editDistanceDPComp(s, t)
|
||||
fmt.Printf("Changing %s to %s requires a minimum of %d edits\n", s, t, res)
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// File: knapsack.go
|
||||
// Created Time: 2023-07-23
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_dynamic_programming
|
||||
|
||||
import "math"
|
||||
|
||||
/* 0-1 knapsack: Brute-force search */
|
||||
func knapsackDFS(wgt, val []int, i, c int) int {
|
||||
// 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
|
||||
no := knapsackDFS(wgt, val, i-1, c)
|
||||
yes := knapsackDFS(wgt, val, i-1, c-wgt[i-1]) + val[i-1]
|
||||
// Return the larger value of the two options
|
||||
return int(math.Max(float64(no), float64(yes)))
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Memoization search */
|
||||
func knapsackDFSMem(wgt, val []int, mem [][]int, i, c int) int {
|
||||
// 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
|
||||
no := knapsackDFSMem(wgt, val, mem, i-1, c)
|
||||
yes := knapsackDFSMem(wgt, val, mem, i-1, c-wgt[i-1]) + val[i-1]
|
||||
// Return the larger value of the two options
|
||||
mem[i][c] = int(math.Max(float64(no), float64(yes)))
|
||||
return mem[i][c]
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Dynamic programming */
|
||||
func knapsackDP(wgt, val []int, cap int) int {
|
||||
n := len(wgt)
|
||||
// Initialize dp table
|
||||
dp := make([][]int, n+1)
|
||||
for i := 0; i <= n; i++ {
|
||||
dp[i] = make([]int, cap+1)
|
||||
}
|
||||
// State transition
|
||||
for i := 1; i <= n; i++ {
|
||||
for 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] = int(math.Max(float64(dp[i-1][c]), float64(dp[i-1][c-wgt[i-1]]+val[i-1])))
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][cap]
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Space-optimized dynamic programming */
|
||||
func knapsackDPComp(wgt, val []int, cap int) int {
|
||||
n := len(wgt)
|
||||
// Initialize dp table
|
||||
dp := make([]int, cap+1)
|
||||
// State transition
|
||||
for i := 1; i <= n; i++ {
|
||||
// Traverse in reverse order
|
||||
for c := cap; c >= 1; c-- {
|
||||
if wgt[i-1] <= c {
|
||||
// The larger value between not selecting and selecting item i
|
||||
dp[c] = int(math.Max(float64(dp[c]), float64(dp[c-wgt[i-1]]+val[i-1])))
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap]
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// File: knapsack_test.go
|
||||
// Created Time: 2023-07-23
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_dynamic_programming
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestKnapsack(t *testing.T) {
|
||||
wgt := []int{10, 20, 30, 40, 50}
|
||||
val := []int{50, 120, 150, 210, 240}
|
||||
c := 50
|
||||
n := len(wgt)
|
||||
|
||||
// Brute-force search
|
||||
res := knapsackDFS(wgt, val, n, c)
|
||||
fmt.Printf("Maximum item value not exceeding knapsack capacity is %d\n", res)
|
||||
|
||||
// Memoization search
|
||||
mem := make([][]int, n+1)
|
||||
for i := 0; i <= n; i++ {
|
||||
mem[i] = make([]int, c+1)
|
||||
for j := 0; j <= c; j++ {
|
||||
mem[i][j] = -1
|
||||
}
|
||||
}
|
||||
res = knapsackDFSMem(wgt, val, mem, n, c)
|
||||
fmt.Printf("Maximum item value not exceeding knapsack capacity is %d\n", res)
|
||||
|
||||
// Dynamic programming
|
||||
res = knapsackDP(wgt, val, c)
|
||||
fmt.Printf("Maximum item value not exceeding knapsack capacity is %d\n", res)
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = knapsackDPComp(wgt, val, c)
|
||||
fmt.Printf("Maximum item value not exceeding knapsack capacity is %d\n", res)
|
||||
}
|
||||
|
||||
func TestUnboundedKnapsack(t *testing.T) {
|
||||
wgt := []int{1, 2, 3}
|
||||
val := []int{5, 11, 15}
|
||||
c := 4
|
||||
|
||||
// Dynamic programming
|
||||
res := unboundedKnapsackDP(wgt, val, c)
|
||||
fmt.Printf("Maximum item value not exceeding knapsack capacity is %d\n", res)
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = unboundedKnapsackDPComp(wgt, val, c)
|
||||
fmt.Printf("Maximum item value not exceeding knapsack capacity is %d\n", res)
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// File: min_cost_climbing_stairs_dp.go
|
||||
// Created Time: 2023-07-23
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_dynamic_programming
|
||||
|
||||
/* Minimum cost climbing stairs: Dynamic programming */
|
||||
func minCostClimbingStairsDP(cost []int) int {
|
||||
n := len(cost) - 1
|
||||
if n == 1 || n == 2 {
|
||||
return cost[n]
|
||||
}
|
||||
min := func(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
dp := make([]int, n+1)
|
||||
// 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 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 */
|
||||
func minCostClimbingStairsDPComp(cost []int) int {
|
||||
n := len(cost) - 1
|
||||
if n == 1 || n == 2 {
|
||||
return cost[n]
|
||||
}
|
||||
min := func(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
// Initial state: preset the solution to the smallest subproblem
|
||||
a, b := cost[1], cost[2]
|
||||
// State transition: gradually solve larger subproblems from smaller ones
|
||||
for i := 3; i <= n; i++ {
|
||||
tmp := b
|
||||
b = min(a, tmp) + cost[i]
|
||||
a = tmp
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
// File: min_path_sum.go
|
||||
// Created Time: 2023-07-23
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_dynamic_programming
|
||||
|
||||
import "math"
|
||||
|
||||
/* Minimum path sum: Brute-force search */
|
||||
func minPathSumDFS(grid [][]int, i, j int) int {
|
||||
// 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 {
|
||||
return math.MaxInt
|
||||
}
|
||||
// Calculate the minimum path cost from top-left to (i-1, j) and (i, j-1)
|
||||
up := minPathSumDFS(grid, i-1, j)
|
||||
left := minPathSumDFS(grid, i, j-1)
|
||||
// Return the minimum path cost from top-left to (i, j)
|
||||
return int(math.Min(float64(left), float64(up))) + grid[i][j]
|
||||
}
|
||||
|
||||
/* Minimum path sum: Memoization search */
|
||||
func minPathSumDFSMem(grid, mem [][]int, i, j int) int {
|
||||
// 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 {
|
||||
return math.MaxInt
|
||||
}
|
||||
// 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
|
||||
up := minPathSumDFSMem(grid, mem, i-1, j)
|
||||
left := minPathSumDFSMem(grid, mem, i, j-1)
|
||||
// Record and return the minimum path cost from top-left to (i, j)
|
||||
mem[i][j] = int(math.Min(float64(left), float64(up))) + grid[i][j]
|
||||
return mem[i][j]
|
||||
}
|
||||
|
||||
/* Minimum path sum: Dynamic programming */
|
||||
func minPathSumDP(grid [][]int) int {
|
||||
n, m := len(grid), len(grid[0])
|
||||
// Initialize dp table
|
||||
dp := make([][]int, n)
|
||||
for i := 0; i < n; i++ {
|
||||
dp[i] = make([]int, m)
|
||||
}
|
||||
dp[0][0] = grid[0][0]
|
||||
// State transition: first row
|
||||
for j := 1; j < m; j++ {
|
||||
dp[0][j] = dp[0][j-1] + grid[0][j]
|
||||
}
|
||||
// State transition: first column
|
||||
for i := 1; i < n; i++ {
|
||||
dp[i][0] = dp[i-1][0] + grid[i][0]
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
for i := 1; i < n; i++ {
|
||||
for j := 1; j < m; j++ {
|
||||
dp[i][j] = int(math.Min(float64(dp[i][j-1]), float64(dp[i-1][j]))) + grid[i][j]
|
||||
}
|
||||
}
|
||||
return dp[n-1][m-1]
|
||||
}
|
||||
|
||||
/* Minimum path sum: Space-optimized dynamic programming */
|
||||
func minPathSumDPComp(grid [][]int) int {
|
||||
n, m := len(grid), len(grid[0])
|
||||
// Initialize dp table
|
||||
dp := make([]int, m)
|
||||
// State transition: first row
|
||||
dp[0] = grid[0][0]
|
||||
for j := 1; j < m; j++ {
|
||||
dp[j] = dp[j-1] + grid[0][j]
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
for i := 1; i < n; i++ {
|
||||
// State transition: first column
|
||||
dp[0] = dp[0] + grid[i][0]
|
||||
// State transition: rest of the columns
|
||||
for j := 1; j < m; j++ {
|
||||
dp[j] = int(math.Min(float64(dp[j-1]), float64(dp[j]))) + grid[i][j]
|
||||
}
|
||||
}
|
||||
return dp[m-1]
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// File: min_path_sum_test.go
|
||||
// Created Time: 2023-07-23
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_dynamic_programming
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMinPathSum(t *testing.T) {
|
||||
grid := [][]int{
|
||||
{1, 3, 1, 5},
|
||||
{2, 2, 4, 2},
|
||||
{5, 3, 2, 1},
|
||||
{4, 3, 5, 2},
|
||||
}
|
||||
n, m := len(grid), len(grid[0])
|
||||
|
||||
// Brute-force search
|
||||
res := minPathSumDFS(grid, n-1, m-1)
|
||||
fmt.Printf("Minimum path sum from top-left to bottom-right is %d\n", res)
|
||||
|
||||
// Memoization search
|
||||
mem := make([][]int, n)
|
||||
for i := 0; i < n; i++ {
|
||||
mem[i] = make([]int, m)
|
||||
for j := 0; j < m; j++ {
|
||||
mem[i][j] = -1
|
||||
}
|
||||
}
|
||||
res = minPathSumDFSMem(grid, mem, n-1, m-1)
|
||||
fmt.Printf("Minimum path sum from top-left to bottom-right is %d\n", res)
|
||||
|
||||
// Dynamic programming
|
||||
res = minPathSumDP(grid)
|
||||
fmt.Printf("Minimum path sum from top-left to bottom-right is %d\n", res)
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = minPathSumDPComp(grid)
|
||||
fmt.Printf("Minimum path sum from top-left to bottom-right is %d\n", res)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// File: unbounded_knapsack.go
|
||||
// Created Time: 2023-07-23
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_dynamic_programming
|
||||
|
||||
import "math"
|
||||
|
||||
/* Unbounded knapsack: Dynamic programming */
|
||||
func unboundedKnapsackDP(wgt, val []int, cap int) int {
|
||||
n := len(wgt)
|
||||
// Initialize dp table
|
||||
dp := make([][]int, n+1)
|
||||
for i := 0; i <= n; i++ {
|
||||
dp[i] = make([]int, cap+1)
|
||||
}
|
||||
// State transition
|
||||
for i := 1; i <= n; i++ {
|
||||
for 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] = int(math.Max(float64(dp[i-1][c]), float64(dp[i][c-wgt[i-1]]+val[i-1])))
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][cap]
|
||||
}
|
||||
|
||||
/* Unbounded knapsack: Space-optimized dynamic programming */
|
||||
func unboundedKnapsackDPComp(wgt, val []int, cap int) int {
|
||||
n := len(wgt)
|
||||
// Initialize dp table
|
||||
dp := make([]int, cap+1)
|
||||
// State transition
|
||||
for i := 1; i <= n; i++ {
|
||||
for 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] = int(math.Max(float64(dp[c]), float64(dp[c-wgt[i-1]]+val[i-1])))
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap]
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// File: graph_adjacency_list.go
|
||||
// Created Time: 2023-01-31
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_graph
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
/* Undirected graph class based on adjacency list */
|
||||
type graphAdjList struct {
|
||||
// Adjacency list, key: vertex, value: all adjacent vertices of that vertex
|
||||
adjList map[Vertex][]Vertex
|
||||
}
|
||||
|
||||
/* Constructor */
|
||||
func newGraphAdjList(edges [][]Vertex) *graphAdjList {
|
||||
g := &graphAdjList{
|
||||
adjList: make(map[Vertex][]Vertex),
|
||||
}
|
||||
// Add all vertices and edges
|
||||
for _, edge := range edges {
|
||||
g.addVertex(edge[0])
|
||||
g.addVertex(edge[1])
|
||||
g.addEdge(edge[0], edge[1])
|
||||
}
|
||||
return g
|
||||
}
|
||||
|
||||
/* Get the number of vertices */
|
||||
func (g *graphAdjList) size() int {
|
||||
return len(g.adjList)
|
||||
}
|
||||
|
||||
/* Add edge */
|
||||
func (g *graphAdjList) addEdge(vet1 Vertex, vet2 Vertex) {
|
||||
_, ok1 := g.adjList[vet1]
|
||||
_, ok2 := g.adjList[vet2]
|
||||
if !ok1 || !ok2 || vet1 == vet2 {
|
||||
panic("error")
|
||||
}
|
||||
// Add edge vet1 - vet2, add anonymous struct{},
|
||||
g.adjList[vet1] = append(g.adjList[vet1], vet2)
|
||||
g.adjList[vet2] = append(g.adjList[vet2], vet1)
|
||||
}
|
||||
|
||||
/* Remove edge */
|
||||
func (g *graphAdjList) removeEdge(vet1 Vertex, vet2 Vertex) {
|
||||
_, ok1 := g.adjList[vet1]
|
||||
_, ok2 := g.adjList[vet2]
|
||||
if !ok1 || !ok2 || vet1 == vet2 {
|
||||
panic("error")
|
||||
}
|
||||
// Remove edge vet1 - vet2
|
||||
g.adjList[vet1] = DeleteSliceElms(g.adjList[vet1], vet2)
|
||||
g.adjList[vet2] = DeleteSliceElms(g.adjList[vet2], vet1)
|
||||
}
|
||||
|
||||
/* Add vertex */
|
||||
func (g *graphAdjList) addVertex(vet Vertex) {
|
||||
_, ok := g.adjList[vet]
|
||||
if ok {
|
||||
return
|
||||
}
|
||||
// Add a new linked list in the adjacency list
|
||||
g.adjList[vet] = make([]Vertex, 0)
|
||||
}
|
||||
|
||||
/* Remove vertex */
|
||||
func (g *graphAdjList) removeVertex(vet Vertex) {
|
||||
_, ok := g.adjList[vet]
|
||||
if !ok {
|
||||
panic("error")
|
||||
}
|
||||
// Remove the linked list corresponding to vertex vet in the adjacency list
|
||||
delete(g.adjList, vet)
|
||||
// Traverse the linked lists of other vertices and remove all edges containing vet
|
||||
for v, list := range g.adjList {
|
||||
g.adjList[v] = DeleteSliceElms(list, vet)
|
||||
}
|
||||
}
|
||||
|
||||
/* Print adjacency list */
|
||||
func (g *graphAdjList) print() {
|
||||
var builder strings.Builder
|
||||
fmt.Printf("Adjacency list = \n")
|
||||
for k, v := range g.adjList {
|
||||
builder.WriteString("\t\t" + strconv.Itoa(k.Val) + ": ")
|
||||
for _, vet := range v {
|
||||
builder.WriteString(strconv.Itoa(vet.Val) + " ")
|
||||
}
|
||||
fmt.Println(builder.String())
|
||||
builder.Reset()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// File: graph_adjacency_list_test.go
|
||||
// Created Time: 2023-01-31
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_graph
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
func TestGraphAdjList(t *testing.T) {
|
||||
/* Add edge */
|
||||
v := ValsToVets([]int{1, 3, 2, 5, 4})
|
||||
edges := [][]Vertex{{v[0], v[1]}, {v[0], v[3]}, {v[1], v[2]}, {v[2], v[3]}, {v[2], v[4]}, {v[3], v[4]}}
|
||||
graph := newGraphAdjList(edges)
|
||||
fmt.Println("After initialization, graph is:")
|
||||
graph.print()
|
||||
|
||||
/* Add edge */
|
||||
// Vertices 1, 3 are v[0], v[1]
|
||||
graph.addEdge(v[0], v[2])
|
||||
fmt.Println("\nAfter adding edge 1-2, graph is")
|
||||
graph.print()
|
||||
|
||||
/* Remove edge */
|
||||
// Vertex 3 is v[1]
|
||||
graph.removeEdge(v[0], v[1])
|
||||
fmt.Println("\nAfter removing edge 1-3, graph is")
|
||||
graph.print()
|
||||
|
||||
/* Add vertex */
|
||||
v5 := NewVertex(6)
|
||||
graph.addVertex(v5)
|
||||
fmt.Println("\nAfter adding vertex 6, graph is")
|
||||
graph.print()
|
||||
|
||||
/* Remove vertex */
|
||||
// Vertex 3 is v[1]
|
||||
graph.removeVertex(v[1])
|
||||
fmt.Println("\nAfter removing vertex 3, graph is")
|
||||
graph.print()
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
// File: graph_adjacency_matrix.go
|
||||
// Created Time: 2023-01-31
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_graph
|
||||
|
||||
import "fmt"
|
||||
|
||||
/* Undirected graph class based on adjacency matrix */
|
||||
type graphAdjMat struct {
|
||||
// Vertex list, where the element represents the "vertex value" and the index represents the "vertex index"
|
||||
vertices []int
|
||||
// Adjacency matrix, where the row and column indices correspond to the "vertex index"
|
||||
adjMat [][]int
|
||||
}
|
||||
|
||||
/* Constructor */
|
||||
func newGraphAdjMat(vertices []int, edges [][]int) *graphAdjMat {
|
||||
// Add vertex
|
||||
n := len(vertices)
|
||||
adjMat := make([][]int, n)
|
||||
for i := range adjMat {
|
||||
adjMat[i] = make([]int, n)
|
||||
}
|
||||
// Initialize graph
|
||||
g := &graphAdjMat{
|
||||
vertices: vertices,
|
||||
adjMat: adjMat,
|
||||
}
|
||||
// Add edge
|
||||
// Note that the edges elements represent vertex indices, i.e., corresponding to the vertices element indices
|
||||
for i := range edges {
|
||||
g.addEdge(edges[i][0], edges[i][1])
|
||||
}
|
||||
return g
|
||||
}
|
||||
|
||||
/* Get the number of vertices */
|
||||
func (g *graphAdjMat) size() int {
|
||||
return len(g.vertices)
|
||||
}
|
||||
|
||||
/* Add vertex */
|
||||
func (g *graphAdjMat) addVertex(val int) {
|
||||
n := g.size()
|
||||
// Add the value of the new vertex to the vertex list
|
||||
g.vertices = append(g.vertices, val)
|
||||
// Add a row to the adjacency matrix
|
||||
newRow := make([]int, n)
|
||||
g.adjMat = append(g.adjMat, newRow)
|
||||
// Add a column to the adjacency matrix
|
||||
for i := range g.adjMat {
|
||||
g.adjMat[i] = append(g.adjMat[i], 0)
|
||||
}
|
||||
}
|
||||
|
||||
/* Remove vertex */
|
||||
func (g *graphAdjMat) removeVertex(index int) {
|
||||
if index >= g.size() {
|
||||
return
|
||||
}
|
||||
// Remove the vertex at index from the vertex list
|
||||
g.vertices = append(g.vertices[:index], g.vertices[index+1:]...)
|
||||
// Remove the row at index from the adjacency matrix
|
||||
g.adjMat = append(g.adjMat[:index], g.adjMat[index+1:]...)
|
||||
// Remove the column at index from the adjacency matrix
|
||||
for i := range g.adjMat {
|
||||
g.adjMat[i] = append(g.adjMat[i][:index], g.adjMat[i][index+1:]...)
|
||||
}
|
||||
}
|
||||
|
||||
/* Add edge */
|
||||
// Parameters i, j correspond to the vertices element indices
|
||||
func (g *graphAdjMat) addEdge(i, j int) {
|
||||
// Handle index out of bounds and equality
|
||||
if i < 0 || j < 0 || i >= g.size() || j >= g.size() || i == j {
|
||||
fmt.Errorf("%s", "Index Out Of Bounds Exception")
|
||||
}
|
||||
// In an undirected graph, the adjacency matrix is symmetric about the main diagonal, i.e., (i, j) == (j, i)
|
||||
g.adjMat[i][j] = 1
|
||||
g.adjMat[j][i] = 1
|
||||
}
|
||||
|
||||
/* Remove edge */
|
||||
// Parameters i, j correspond to the vertices element indices
|
||||
func (g *graphAdjMat) removeEdge(i, j int) {
|
||||
// Handle index out of bounds and equality
|
||||
if i < 0 || j < 0 || i >= g.size() || j >= g.size() || i == j {
|
||||
fmt.Errorf("%s", "Index Out Of Bounds Exception")
|
||||
}
|
||||
g.adjMat[i][j] = 0
|
||||
g.adjMat[j][i] = 0
|
||||
}
|
||||
|
||||
/* Print adjacency matrix */
|
||||
func (g *graphAdjMat) print() {
|
||||
fmt.Printf("\tVertex list = %v\n", g.vertices)
|
||||
fmt.Printf("\tAdjacency matrix = \n")
|
||||
for i := range g.adjMat {
|
||||
fmt.Printf("\t\t\t%v\n", g.adjMat[i])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// File: graph_adjacency_matrix_test.go
|
||||
// Created Time: 2023-01-31
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_graph
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGraphAdjMat(t *testing.T) {
|
||||
/* Add edge */
|
||||
// Note that the edges elements represent vertex indices, i.e., corresponding to the vertices element indices
|
||||
vertices := []int{1, 3, 2, 5, 4}
|
||||
edges := [][]int{{0, 1}, {1, 2}, {2, 3}, {0, 3}, {2, 4}, {3, 4}}
|
||||
graph := newGraphAdjMat(vertices, edges)
|
||||
fmt.Println("After initialization, graph is:")
|
||||
graph.print()
|
||||
|
||||
/* Add edge */
|
||||
// Add vertex
|
||||
graph.addEdge(0, 2)
|
||||
fmt.Println("After adding edge 1-2, graph is")
|
||||
graph.print()
|
||||
|
||||
/* Remove edge */
|
||||
// Vertices 1, 3 have indices 0, 1 respectively
|
||||
graph.removeEdge(0, 1)
|
||||
fmt.Println("After removing edge 1-3, graph is")
|
||||
graph.print()
|
||||
|
||||
/* Add vertex */
|
||||
graph.addVertex(6)
|
||||
fmt.Println("After adding vertex 6, graph is")
|
||||
graph.print()
|
||||
|
||||
/* Remove vertex */
|
||||
// Vertex 3 has index 1
|
||||
graph.removeVertex(1)
|
||||
fmt.Println("After removing vertex 3, graph is")
|
||||
graph.print()
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// File: graph_bfs.go
|
||||
// Created Time: 2023-02-18
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_graph
|
||||
|
||||
import (
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
/* Breadth-first traversal */
|
||||
// Use adjacency list to represent the graph, in order to obtain all adjacent vertices of a specified vertex
|
||||
func graphBFS(g *graphAdjList, startVet Vertex) []Vertex {
|
||||
// Vertex traversal sequence
|
||||
res := make([]Vertex, 0)
|
||||
// Hash set for recording vertices that have been visited
|
||||
visited := make(map[Vertex]struct{})
|
||||
visited[startVet] = struct{}{}
|
||||
// Queue used to implement BFS, using slice to simulate queue
|
||||
queue := make([]Vertex, 0)
|
||||
queue = append(queue, startVet)
|
||||
// Starting from vertex vet, loop until all vertices are visited
|
||||
for len(queue) > 0 {
|
||||
// Dequeue the front vertex
|
||||
vet := queue[0]
|
||||
queue = queue[1:]
|
||||
// Record visited vertex
|
||||
res = append(res, vet)
|
||||
// Traverse all adjacent vertices of this vertex
|
||||
for _, adjVet := range g.adjList[vet] {
|
||||
_, isExist := visited[adjVet]
|
||||
// Only enqueue unvisited vertices
|
||||
if !isExist {
|
||||
queue = append(queue, adjVet)
|
||||
visited[adjVet] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Return vertex traversal sequence
|
||||
return res
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// File: graph_bfs_test.go
|
||||
// Created Time: 2023-02-18
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_graph
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
func TestGraphBFS(t *testing.T) {
|
||||
/* Add edge */
|
||||
vets := ValsToVets([]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
|
||||
edges := [][]Vertex{
|
||||
{vets[0], vets[1]}, {vets[0], vets[3]}, {vets[1], vets[2]}, {vets[1], vets[4]},
|
||||
{vets[2], vets[5]}, {vets[3], vets[4]}, {vets[3], vets[6]}, {vets[4], vets[5]},
|
||||
{vets[4], vets[7]}, {vets[5], vets[8]}, {vets[6], vets[7]}, {vets[7], vets[8]}}
|
||||
graph := newGraphAdjList(edges)
|
||||
fmt.Println("After initialization, graph is:")
|
||||
graph.print()
|
||||
|
||||
/* Breadth-first traversal */
|
||||
res := graphBFS(graph, vets[0])
|
||||
fmt.Println("Breadth-first traversal (BFS) vertex sequence is:")
|
||||
PrintSlice(VetsToVals(res))
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// File: graph_dfs.go
|
||||
// Created Time: 2023-02-18
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_graph
|
||||
|
||||
import (
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
/* Depth-first traversal helper function */
|
||||
func dfs(g *graphAdjList, visited map[Vertex]struct{}, res *[]Vertex, vet Vertex) {
|
||||
// append operation returns a new reference, must reassign original reference to new slice's reference
|
||||
*res = append(*res, vet)
|
||||
visited[vet] = struct{}{}
|
||||
// Traverse all adjacent vertices of this vertex
|
||||
for _, adjVet := range g.adjList[vet] {
|
||||
_, isExist := visited[adjVet]
|
||||
// Recursively visit adjacent vertices
|
||||
if !isExist {
|
||||
dfs(g, visited, res, adjVet)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Depth-first traversal */
|
||||
// Use adjacency list to represent the graph, in order to obtain all adjacent vertices of a specified vertex
|
||||
func graphDFS(g *graphAdjList, startVet Vertex) []Vertex {
|
||||
// Vertex traversal sequence
|
||||
res := make([]Vertex, 0)
|
||||
// Hash set for recording vertices that have been visited
|
||||
visited := make(map[Vertex]struct{})
|
||||
dfs(g, visited, &res, startVet)
|
||||
// Return vertex traversal sequence
|
||||
return res
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// File: graph_dfs_test.go
|
||||
// Created Time: 2023-02-18
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_graph
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
func TestGraphDFS(t *testing.T) {
|
||||
/* Add edge */
|
||||
vets := ValsToVets([]int{0, 1, 2, 3, 4, 5, 6})
|
||||
edges := [][]Vertex{
|
||||
{vets[0], vets[1]}, {vets[0], vets[3]}, {vets[1], vets[2]},
|
||||
{vets[2], vets[5]}, {vets[4], vets[5]}, {vets[5], vets[6]}}
|
||||
graph := newGraphAdjList(edges)
|
||||
fmt.Println("After initialization, graph is:")
|
||||
graph.print()
|
||||
|
||||
/* Depth-first traversal */
|
||||
res := graphDFS(graph, vets[0])
|
||||
fmt.Println("Depth-first traversal (DFS) vertex sequence is:")
|
||||
PrintSlice(VetsToVals(res))
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// File: coin_change_greedy.go
|
||||
// Created Time: 2023-07-23
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_greedy
|
||||
|
||||
/* Coin change: Greedy algorithm */
|
||||
func coinChangeGreedy(coins []int, amt int) int {
|
||||
// Assume coins list is sorted
|
||||
i := len(coins) - 1
|
||||
count := 0
|
||||
// Loop to make greedy choices until no remaining amount
|
||||
for amt > 0 {
|
||||
// Find the coin that is less than and closest to the remaining amount
|
||||
for i > 0 && coins[i] > amt {
|
||||
i--
|
||||
}
|
||||
// Choose coins[i]
|
||||
amt -= coins[i]
|
||||
count++
|
||||
}
|
||||
// If no feasible solution is found, return -1
|
||||
if amt != 0 {
|
||||
return -1
|
||||
}
|
||||
return count
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// File: coin_change_greedy_test.go
|
||||
// Created Time: 2023-07-23
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_greedy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCoinChangeGreedy(t *testing.T) {
|
||||
// Greedy algorithm: Can guarantee finding the global optimal solution
|
||||
coins := []int{1, 5, 10, 20, 50, 100}
|
||||
amt := 186
|
||||
res := coinChangeGreedy(coins, amt)
|
||||
fmt.Printf("coins = %v, amt = %d\n", coins, amt)
|
||||
fmt.Printf("Minimum number of coins needed to make %d is %d\n", amt, res)
|
||||
|
||||
// Greedy algorithm: Cannot guarantee finding the global optimal solution
|
||||
coins = []int{1, 20, 50}
|
||||
amt = 60
|
||||
res = coinChangeGreedy(coins, amt)
|
||||
fmt.Printf("coins = %v, amt = %d\n", coins, amt)
|
||||
fmt.Printf("Minimum number of coins needed to make %d is %d\n", amt, res)
|
||||
fmt.Println("Actually the minimum number needed is 3, i.e., 20 + 20 + 20")
|
||||
|
||||
// Greedy algorithm: Cannot guarantee finding the global optimal solution
|
||||
coins = []int{1, 49, 50}
|
||||
amt = 98
|
||||
res = coinChangeGreedy(coins, amt)
|
||||
fmt.Printf("coins = %v, amt = %d\n", coins, amt)
|
||||
fmt.Printf("Minimum number of coins needed to make %d is %d\n", amt, res)
|
||||
fmt.Println("Actually the minimum number needed is 2, i.e., 49 + 49")
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// File: fractional_knapsack.go
|
||||
// Created Time: 2023-07-23
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_greedy
|
||||
|
||||
import "sort"
|
||||
|
||||
/* Item */
|
||||
type Item struct {
|
||||
w int // Item weight
|
||||
v int // Item value
|
||||
}
|
||||
|
||||
/* Fractional knapsack: Greedy algorithm */
|
||||
func fractionalKnapsack(wgt []int, val []int, cap int) float64 {
|
||||
// Create item list with two attributes: weight, value
|
||||
items := make([]Item, len(wgt))
|
||||
for i := 0; i < len(wgt); i++ {
|
||||
items[i] = Item{wgt[i], val[i]}
|
||||
}
|
||||
// Sort by unit value item.v / item.w from high to low
|
||||
sort.Slice(items, func(i, j int) bool {
|
||||
return float64(items[i].v)/float64(items[i].w) > float64(items[j].v)/float64(items[j].w)
|
||||
})
|
||||
// Loop for greedy selection
|
||||
res := 0.0
|
||||
for _, item := range items {
|
||||
if item.w <= cap {
|
||||
// If remaining capacity is sufficient, put the entire current item into the knapsack
|
||||
res += float64(item.v)
|
||||
cap -= item.w
|
||||
} else {
|
||||
// If remaining capacity is insufficient, put part of the current item into the knapsack
|
||||
res += float64(item.v) / float64(item.w) * float64(cap)
|
||||
// No remaining capacity, so break out of the loop
|
||||
break
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// File: fractional_knapsack_test.go
|
||||
// Created Time: 2023-07-23
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_greedy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFractionalKnapsack(t *testing.T) {
|
||||
wgt := []int{10, 20, 30, 40, 50}
|
||||
val := []int{50, 120, 150, 210, 240}
|
||||
capacity := 50
|
||||
|
||||
// Greedy algorithm
|
||||
res := fractionalKnapsack(wgt, val, capacity)
|
||||
fmt.Println("Maximum item value not exceeding knapsack capacity is", res)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// File: max_capacity.go
|
||||
// Created Time: 2023-07-23
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_greedy
|
||||
|
||||
import "math"
|
||||
|
||||
/* Max capacity: Greedy algorithm */
|
||||
func maxCapacity(ht []int) int {
|
||||
// Initialize i, j to be at both ends of the array
|
||||
i, j := 0, len(ht)-1
|
||||
// Initial max capacity is 0
|
||||
res := 0
|
||||
// Loop for greedy selection until the two boards meet
|
||||
for i < j {
|
||||
// Update max capacity
|
||||
capacity := int(math.Min(float64(ht[i]), float64(ht[j]))) * (j - i)
|
||||
res = int(math.Max(float64(res), float64(capacity)))
|
||||
// Move the shorter board inward
|
||||
if ht[i] < ht[j] {
|
||||
i++
|
||||
} else {
|
||||
j--
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// File: max_capacity_test.go
|
||||
// Created Time: 2023-07-23
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_greedy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMaxCapacity(t *testing.T) {
|
||||
ht := []int{3, 8, 5, 2, 7, 7, 3, 4}
|
||||
|
||||
// Greedy algorithm
|
||||
res := maxCapacity(ht)
|
||||
fmt.Println("Maximum capacity is", res)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// File: max_product_cutting.go
|
||||
// Created Time: 2023-07-23
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_greedy
|
||||
|
||||
import "math"
|
||||
|
||||
/* Max product cutting: Greedy algorithm */
|
||||
func maxProductCutting(n int) int {
|
||||
// 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
|
||||
a := n / 3
|
||||
b := n % 3
|
||||
if b == 1 {
|
||||
// When the remainder is 1, convert a pair of 1 * 3 to 2 * 2
|
||||
return int(math.Pow(3, float64(a-1))) * 2 * 2
|
||||
}
|
||||
if b == 2 {
|
||||
// When the remainder is 2, do nothing
|
||||
return int(math.Pow(3, float64(a))) * 2
|
||||
}
|
||||
// When the remainder is 0, do nothing
|
||||
return int(math.Pow(3, float64(a)))
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// File: max_product_cutting_test.go
|
||||
// Created Time: 2023-07-23
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_greedy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMaxProductCutting(t *testing.T) {
|
||||
n := 58
|
||||
// Greedy algorithm
|
||||
res := maxProductCutting(n)
|
||||
fmt.Println("Maximum cutting product is", res)
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
// File: array_hash_map.go
|
||||
// Created Time: 2022-12-14
|
||||
// Author: msk397 (machangxinq@gmail.com)
|
||||
|
||||
package chapter_hashing
|
||||
|
||||
import "fmt"
|
||||
|
||||
/* Key-value pair */
|
||||
type pair struct {
|
||||
key int
|
||||
val string
|
||||
}
|
||||
|
||||
/* Hash table based on array implementation */
|
||||
type arrayHashMap struct {
|
||||
buckets []*pair
|
||||
}
|
||||
|
||||
/* Initialize hash table */
|
||||
func newArrayHashMap() *arrayHashMap {
|
||||
// Initialize array with 100 buckets
|
||||
buckets := make([]*pair, 100)
|
||||
return &arrayHashMap{buckets: buckets}
|
||||
}
|
||||
|
||||
/* Hash function */
|
||||
func (a *arrayHashMap) hashFunc(key int) int {
|
||||
index := key % 100
|
||||
return index
|
||||
}
|
||||
|
||||
/* Query operation */
|
||||
func (a *arrayHashMap) get(key int) string {
|
||||
index := a.hashFunc(key)
|
||||
pair := a.buckets[index]
|
||||
if pair == nil {
|
||||
return "Not Found"
|
||||
}
|
||||
return pair.val
|
||||
}
|
||||
|
||||
/* Add operation */
|
||||
func (a *arrayHashMap) put(key int, val string) {
|
||||
pair := &pair{key: key, val: val}
|
||||
index := a.hashFunc(key)
|
||||
a.buckets[index] = pair
|
||||
}
|
||||
|
||||
/* Remove operation */
|
||||
func (a *arrayHashMap) remove(key int) {
|
||||
index := a.hashFunc(key)
|
||||
// Set to nil to delete
|
||||
a.buckets[index] = nil
|
||||
}
|
||||
|
||||
/* Get all key pairs */
|
||||
func (a *arrayHashMap) pairSet() []*pair {
|
||||
var pairs []*pair
|
||||
for _, pair := range a.buckets {
|
||||
if pair != nil {
|
||||
pairs = append(pairs, pair)
|
||||
}
|
||||
}
|
||||
return pairs
|
||||
}
|
||||
|
||||
/* Get all keys */
|
||||
func (a *arrayHashMap) keySet() []int {
|
||||
var keys []int
|
||||
for _, pair := range a.buckets {
|
||||
if pair != nil {
|
||||
keys = append(keys, pair.key)
|
||||
}
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
/* Get all values */
|
||||
func (a *arrayHashMap) valueSet() []string {
|
||||
var values []string
|
||||
for _, pair := range a.buckets {
|
||||
if pair != nil {
|
||||
values = append(values, pair.val)
|
||||
}
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
/* Print hash table */
|
||||
func (a *arrayHashMap) print() {
|
||||
for _, pair := range a.buckets {
|
||||
if pair != nil {
|
||||
fmt.Println(pair.key, "->", pair.val)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// File: array_hash_map_test.go
|
||||
// Created Time: 2022-12-14
|
||||
// Author: msk397 (machangxinq@gmail.com)
|
||||
|
||||
package chapter_hashing
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestArrayHashMap(t *testing.T) {
|
||||
/* Initialize hash table */
|
||||
hmap := newArrayHashMap()
|
||||
|
||||
/* Add operation */
|
||||
// Add key-value pair (key, value) to the hash table
|
||||
hmap.put(12836, "Xiao Ha")
|
||||
hmap.put(15937, "Xiao Luo")
|
||||
hmap.put(16750, "Xiao Suan")
|
||||
hmap.put(13276, "Xiao Fa")
|
||||
hmap.put(10583, "Xiao Ya")
|
||||
fmt.Println("\nAfter adding is complete, hash table is\nKey -> Value")
|
||||
hmap.print()
|
||||
|
||||
/* Query operation */
|
||||
// Input key into hash table to get value
|
||||
name := hmap.get(15937)
|
||||
fmt.Println("\nInput student ID 15937, query name " + name)
|
||||
|
||||
/* Remove operation */
|
||||
// Remove key-value pair (key, value) from hash table
|
||||
hmap.remove(10583)
|
||||
fmt.Println("\nAfter removing 10583, hash table is\nKey -> Value")
|
||||
hmap.print()
|
||||
|
||||
/* Traverse hash table */
|
||||
fmt.Println("\nTraverse key-value pairs Key->Value")
|
||||
for _, kv := range hmap.pairSet() {
|
||||
fmt.Println(kv.key, " -> ", kv.val)
|
||||
}
|
||||
|
||||
fmt.Println("\nTraverse keys only Key")
|
||||
for _, key := range hmap.keySet() {
|
||||
fmt.Println(key)
|
||||
}
|
||||
|
||||
fmt.Println("\nTraverse values only Value")
|
||||
for _, val := range hmap.valueSet() {
|
||||
fmt.Println(val)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// File: hash_collision_test.go
|
||||
// Created Time: 2022-12-14
|
||||
// Author: msk397 (machangxinq@gmail.com)
|
||||
|
||||
package chapter_hashing
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHashMapChaining(t *testing.T) {
|
||||
/* Initialize hash table */
|
||||
hmap := newHashMapChaining()
|
||||
|
||||
/* Add operation */
|
||||
// Add key-value pair (key, value) to the hash table
|
||||
hmap.put(12836, "Xiao Ha")
|
||||
hmap.put(15937, "Xiao Luo")
|
||||
hmap.put(16750, "Xiao Suan")
|
||||
hmap.put(13276, "Xiao Fa")
|
||||
hmap.put(10583, "Xiao Ya")
|
||||
fmt.Println("\nAfter adding is complete, hash table is\nKey -> Value")
|
||||
hmap.print()
|
||||
|
||||
/* Query operation */
|
||||
// Input key into hash table to get value
|
||||
name := hmap.get(15937)
|
||||
fmt.Println("\nInput student ID 15937, found name", name)
|
||||
|
||||
/* Remove operation */
|
||||
// Remove key-value pair (key, value) from hash table
|
||||
hmap.remove(12836)
|
||||
fmt.Println("\nAfter removing 12836, hash table is\nKey -> Value")
|
||||
hmap.print()
|
||||
}
|
||||
|
||||
func TestHashMapOpenAddressing(t *testing.T) {
|
||||
/* Initialize hash table */
|
||||
hmap := newHashMapOpenAddressing()
|
||||
|
||||
/* Add operation */
|
||||
// Add key-value pair (key, value) to the hash table
|
||||
hmap.put(12836, "Xiao Ha")
|
||||
hmap.put(15937, "Xiao Luo")
|
||||
hmap.put(16750, "Xiao Suan")
|
||||
hmap.put(13276, "Xiao Fa")
|
||||
hmap.put(10583, "Xiao Ya")
|
||||
fmt.Println("\nAfter adding is complete, hash table is\nKey -> Value")
|
||||
hmap.print()
|
||||
|
||||
/* Query operation */
|
||||
// Input key into hash table to get value
|
||||
name := hmap.get(13276)
|
||||
fmt.Println("\nInput student ID 13276, query name ", name)
|
||||
|
||||
/* Remove operation */
|
||||
// Remove key-value pair (key, value) from hash table
|
||||
hmap.remove(16750)
|
||||
fmt.Println("\nAfter removing 16750, hash table is\nKey -> Value")
|
||||
hmap.print()
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
// File: hash_map_chaining.go
|
||||
// Created Time: 2023-06-23
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_hashing
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
/* Hash table with separate chaining */
|
||||
type hashMapChaining struct {
|
||||
size int // Number of key-value pairs
|
||||
capacity int // Hash table capacity
|
||||
loadThres float64 // Load factor threshold for triggering expansion
|
||||
extendRatio int // Expansion multiplier
|
||||
buckets [][]pair // Bucket array
|
||||
}
|
||||
|
||||
/* Constructor */
|
||||
func newHashMapChaining() *hashMapChaining {
|
||||
buckets := make([][]pair, 4)
|
||||
for i := 0; i < 4; i++ {
|
||||
buckets[i] = make([]pair, 0)
|
||||
}
|
||||
return &hashMapChaining{
|
||||
size: 0,
|
||||
capacity: 4,
|
||||
loadThres: 2.0 / 3.0,
|
||||
extendRatio: 2,
|
||||
buckets: buckets,
|
||||
}
|
||||
}
|
||||
|
||||
/* Hash function */
|
||||
func (m *hashMapChaining) hashFunc(key int) int {
|
||||
return key % m.capacity
|
||||
}
|
||||
|
||||
/* Load factor */
|
||||
func (m *hashMapChaining) loadFactor() float64 {
|
||||
return float64(m.size) / float64(m.capacity)
|
||||
}
|
||||
|
||||
/* Query operation */
|
||||
func (m *hashMapChaining) get(key int) string {
|
||||
idx := m.hashFunc(key)
|
||||
bucket := m.buckets[idx]
|
||||
// Traverse bucket, if key is found, return corresponding val
|
||||
for _, p := range bucket {
|
||||
if p.key == key {
|
||||
return p.val
|
||||
}
|
||||
}
|
||||
// Return empty string if key not found
|
||||
return ""
|
||||
}
|
||||
|
||||
/* Add operation */
|
||||
func (m *hashMapChaining) put(key int, val string) {
|
||||
// When load factor exceeds threshold, perform expansion
|
||||
if m.loadFactor() > m.loadThres {
|
||||
m.extend()
|
||||
}
|
||||
idx := m.hashFunc(key)
|
||||
// Traverse bucket, if specified key is encountered, update corresponding val and return
|
||||
for i := range m.buckets[idx] {
|
||||
if m.buckets[idx][i].key == key {
|
||||
m.buckets[idx][i].val = val
|
||||
return
|
||||
}
|
||||
}
|
||||
// If key does not exist, append key-value pair to the end
|
||||
p := pair{
|
||||
key: key,
|
||||
val: val,
|
||||
}
|
||||
m.buckets[idx] = append(m.buckets[idx], p)
|
||||
m.size += 1
|
||||
}
|
||||
|
||||
/* Remove operation */
|
||||
func (m *hashMapChaining) remove(key int) {
|
||||
idx := m.hashFunc(key)
|
||||
// Traverse bucket and remove key-value pair from it
|
||||
for i, p := range m.buckets[idx] {
|
||||
if p.key == key {
|
||||
// Slice deletion
|
||||
m.buckets[idx] = append(m.buckets[idx][:i], m.buckets[idx][i+1:]...)
|
||||
m.size -= 1
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Expand hash table */
|
||||
func (m *hashMapChaining) extend() {
|
||||
// Temporarily store the original hash table
|
||||
tmpBuckets := make([][]pair, len(m.buckets))
|
||||
for i := 0; i < len(m.buckets); i++ {
|
||||
tmpBuckets[i] = make([]pair, len(m.buckets[i]))
|
||||
copy(tmpBuckets[i], m.buckets[i])
|
||||
}
|
||||
// Initialize expanded new hash table
|
||||
m.capacity *= m.extendRatio
|
||||
m.buckets = make([][]pair, m.capacity)
|
||||
for i := 0; i < m.capacity; i++ {
|
||||
m.buckets[i] = make([]pair, 0)
|
||||
}
|
||||
m.size = 0
|
||||
// Move key-value pairs from original hash table to new hash table
|
||||
for _, bucket := range tmpBuckets {
|
||||
for _, p := range bucket {
|
||||
m.put(p.key, p.val)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Print hash table */
|
||||
func (m *hashMapChaining) print() {
|
||||
var builder strings.Builder
|
||||
|
||||
for _, bucket := range m.buckets {
|
||||
builder.WriteString("[")
|
||||
for _, p := range bucket {
|
||||
builder.WriteString(strconv.Itoa(p.key) + " -> " + p.val + " ")
|
||||
}
|
||||
builder.WriteString("]")
|
||||
fmt.Println(builder.String())
|
||||
builder.Reset()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
// File: hash_map_open_addressing.go
|
||||
// Created Time: 2023-06-23
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_hashing
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
/* Hash table with open addressing */
|
||||
type hashMapOpenAddressing struct {
|
||||
size int // Number of key-value pairs
|
||||
capacity int // Hash table capacity
|
||||
loadThres float64 // Load factor threshold for triggering expansion
|
||||
extendRatio int // Expansion multiplier
|
||||
buckets []*pair // Bucket array
|
||||
TOMBSTONE *pair // Removal marker
|
||||
}
|
||||
|
||||
/* Constructor */
|
||||
func newHashMapOpenAddressing() *hashMapOpenAddressing {
|
||||
return &hashMapOpenAddressing{
|
||||
size: 0,
|
||||
capacity: 4,
|
||||
loadThres: 2.0 / 3.0,
|
||||
extendRatio: 2,
|
||||
buckets: make([]*pair, 4),
|
||||
TOMBSTONE: &pair{-1, "-1"},
|
||||
}
|
||||
}
|
||||
|
||||
/* Hash function */
|
||||
func (h *hashMapOpenAddressing) hashFunc(key int) int {
|
||||
return key % h.capacity // Calculate hash value based on key
|
||||
}
|
||||
|
||||
/* Load factor */
|
||||
func (h *hashMapOpenAddressing) loadFactor() float64 {
|
||||
return float64(h.size) / float64(h.capacity) // Calculate current load factor
|
||||
}
|
||||
|
||||
/* Search for bucket index corresponding to key */
|
||||
func (h *hashMapOpenAddressing) findBucket(key int) int {
|
||||
index := h.hashFunc(key) // Get initial index
|
||||
firstTombstone := -1 // Record position of first TOMBSTONE encountered
|
||||
for h.buckets[index] != nil {
|
||||
if h.buckets[index].key == key {
|
||||
if firstTombstone != -1 {
|
||||
// If a removal marker was encountered before, move the key-value pair to that index
|
||||
h.buckets[firstTombstone] = h.buckets[index]
|
||||
h.buckets[index] = h.TOMBSTONE
|
||||
return firstTombstone // Return the moved bucket index
|
||||
}
|
||||
return index // Return found index
|
||||
}
|
||||
if firstTombstone == -1 && h.buckets[index] == h.TOMBSTONE {
|
||||
firstTombstone = index // Record position of first deletion marker encountered
|
||||
}
|
||||
index = (index + 1) % h.capacity // Linear probing, wrap around to head if past tail
|
||||
}
|
||||
// If key does not exist, return the index for insertion
|
||||
if firstTombstone != -1 {
|
||||
return firstTombstone
|
||||
}
|
||||
return index
|
||||
}
|
||||
|
||||
/* Query operation */
|
||||
func (h *hashMapOpenAddressing) get(key int) string {
|
||||
index := h.findBucket(key) // Search for bucket index corresponding to key
|
||||
if h.buckets[index] != nil && h.buckets[index] != h.TOMBSTONE {
|
||||
return h.buckets[index].val // If key-value pair is found, return corresponding val
|
||||
}
|
||||
return "" // Return "" if key-value pair does not exist
|
||||
}
|
||||
|
||||
/* Add operation */
|
||||
func (h *hashMapOpenAddressing) put(key int, val string) {
|
||||
if h.loadFactor() > h.loadThres {
|
||||
h.extend() // When load factor exceeds threshold, perform expansion
|
||||
}
|
||||
index := h.findBucket(key) // Search for bucket index corresponding to key
|
||||
if h.buckets[index] == nil || h.buckets[index] == h.TOMBSTONE {
|
||||
h.buckets[index] = &pair{key, val} // If key-value pair does not exist, add the key-value pair
|
||||
h.size++
|
||||
} else {
|
||||
h.buckets[index].val = val // If key-value pair found, overwrite val
|
||||
}
|
||||
}
|
||||
|
||||
/* Remove operation */
|
||||
func (h *hashMapOpenAddressing) remove(key int) {
|
||||
index := h.findBucket(key) // Search for bucket index corresponding to key
|
||||
if h.buckets[index] != nil && h.buckets[index] != h.TOMBSTONE {
|
||||
h.buckets[index] = h.TOMBSTONE // If key-value pair is found, overwrite it with removal marker
|
||||
h.size--
|
||||
}
|
||||
}
|
||||
|
||||
/* Expand hash table */
|
||||
func (h *hashMapOpenAddressing) extend() {
|
||||
oldBuckets := h.buckets // Temporarily store the original hash table
|
||||
h.capacity *= h.extendRatio // Update capacity
|
||||
h.buckets = make([]*pair, h.capacity) // Initialize expanded new hash table
|
||||
h.size = 0 // Reset size
|
||||
// Move key-value pairs from original hash table to new hash table
|
||||
for _, pair := range oldBuckets {
|
||||
if pair != nil && pair != h.TOMBSTONE {
|
||||
h.put(pair.key, pair.val)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Print hash table */
|
||||
func (h *hashMapOpenAddressing) print() {
|
||||
for _, pair := range h.buckets {
|
||||
if pair == nil {
|
||||
fmt.Println("nil")
|
||||
} else if pair == h.TOMBSTONE {
|
||||
fmt.Println("TOMBSTONE")
|
||||
} else {
|
||||
fmt.Printf("%d -> %s\n", pair.key, pair.val)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// File: hash_map_test.go
|
||||
// Created Time: 2022-12-14
|
||||
// Author: msk397 (machangxinq@gmail.com)
|
||||
|
||||
package chapter_hashing
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
func TestHashMap(t *testing.T) {
|
||||
/* Initialize hash table */
|
||||
hmap := make(map[int]string)
|
||||
|
||||
/* Add operation */
|
||||
// Add key-value pair (key, value) to the hash table
|
||||
hmap[12836] = "Xiao Ha"
|
||||
hmap[15937] = "Xiao Luo"
|
||||
hmap[16750] = "Xiao Suan"
|
||||
hmap[13276] = "Xiao Fa"
|
||||
hmap[10583] = "Xiao Ya"
|
||||
fmt.Println("\nAfter adding is complete, hash table is\nKey -> Value")
|
||||
PrintMap(hmap)
|
||||
|
||||
/* Query operation */
|
||||
// Input key into hash table to get value
|
||||
name := hmap[15937]
|
||||
fmt.Println("\nInput student ID 15937, query name ", name)
|
||||
|
||||
/* Remove operation */
|
||||
// Remove key-value pair (key, value) from hash table
|
||||
delete(hmap, 10583)
|
||||
fmt.Println("\nAfter removing 10583, hash table is\nKey -> Value")
|
||||
PrintMap(hmap)
|
||||
|
||||
/* Traverse hash table */
|
||||
// Traverse key-value pairs
|
||||
fmt.Println("\nTraverse key-value pairs Key->Value")
|
||||
for key, value := range hmap {
|
||||
fmt.Println(key, "->", value)
|
||||
}
|
||||
// Traverse keys only
|
||||
fmt.Println("\nTraverse keys only Key")
|
||||
for key := range hmap {
|
||||
fmt.Println(key)
|
||||
}
|
||||
// Traverse values only
|
||||
fmt.Println("\nTraverse values only Value")
|
||||
for _, value := range hmap {
|
||||
fmt.Println(value)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimpleHash(t *testing.T) {
|
||||
var hash int
|
||||
|
||||
key := "Hello Algo"
|
||||
|
||||
hash = addHash(key)
|
||||
fmt.Println("Additive hash value is " + strconv.Itoa(hash))
|
||||
|
||||
hash = mulHash(key)
|
||||
fmt.Println("Multiplicative hash value is " + strconv.Itoa(hash))
|
||||
|
||||
hash = xorHash(key)
|
||||
fmt.Println("XOR hash value is " + strconv.Itoa(hash))
|
||||
|
||||
hash = rotHash(key)
|
||||
fmt.Println("Rotational hash value is " + strconv.Itoa(hash))
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// File: simple_hash.go
|
||||
// Created Time: 2023-06-23
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_hashing
|
||||
|
||||
import "fmt"
|
||||
|
||||
/* Additive hash */
|
||||
func addHash(key string) int {
|
||||
var hash int64
|
||||
var modulus int64
|
||||
|
||||
modulus = 1000000007
|
||||
for _, b := range []byte(key) {
|
||||
hash = (hash + int64(b)) % modulus
|
||||
}
|
||||
return int(hash)
|
||||
}
|
||||
|
||||
/* Multiplicative hash */
|
||||
func mulHash(key string) int {
|
||||
var hash int64
|
||||
var modulus int64
|
||||
|
||||
modulus = 1000000007
|
||||
for _, b := range []byte(key) {
|
||||
hash = (31*hash + int64(b)) % modulus
|
||||
}
|
||||
return int(hash)
|
||||
}
|
||||
|
||||
/* XOR hash */
|
||||
func xorHash(key string) int {
|
||||
hash := 0
|
||||
modulus := 1000000007
|
||||
for _, b := range []byte(key) {
|
||||
fmt.Println(int(b))
|
||||
hash ^= int(b)
|
||||
hash = (31*hash + int(b)) % modulus
|
||||
}
|
||||
return hash & modulus
|
||||
}
|
||||
|
||||
/* Rotational hash */
|
||||
func rotHash(key string) int {
|
||||
var hash int64
|
||||
var modulus int64
|
||||
|
||||
modulus = 1000000007
|
||||
for _, b := range []byte(key) {
|
||||
hash = ((hash << 4) ^ (hash >> 28) ^ int64(b)) % modulus
|
||||
}
|
||||
return int(hash)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// File: heap.go
|
||||
// Created Time: 2023-01-12
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_heap
|
||||
|
||||
// In Go, integer max heap can be built by implementing heap.Interface
|
||||
// Implementing heap.Interface requires also implementing sort.Interface
|
||||
type intHeap []any
|
||||
|
||||
// Push function of heap.Interface, implements pushing element to heap
|
||||
func (h *intHeap) Push(x any) {
|
||||
// Push and Pop use pointer receiver as parameter
|
||||
// Because they not only adjust the slice content, but also modify the slice length.
|
||||
*h = append(*h, x.(int))
|
||||
}
|
||||
|
||||
// Pop function of heap.Interface, implements popping heap top element
|
||||
func (h *intHeap) Pop() any {
|
||||
// Element to be popped is stored at the end
|
||||
last := (*h)[len(*h)-1]
|
||||
*h = (*h)[:len(*h)-1]
|
||||
return last
|
||||
}
|
||||
|
||||
// Len function of sort.Interface
|
||||
func (h *intHeap) Len() int {
|
||||
return len(*h)
|
||||
}
|
||||
|
||||
// Less function of sort.Interface
|
||||
func (h *intHeap) Less(i, j int) bool {
|
||||
// If implementing min heap, need to change to less than sign
|
||||
return (*h)[i].(int) > (*h)[j].(int)
|
||||
}
|
||||
|
||||
// Swap function of sort.Interface
|
||||
func (h *intHeap) Swap(i, j int) {
|
||||
(*h)[i], (*h)[j] = (*h)[j], (*h)[i]
|
||||
}
|
||||
|
||||
// Top gets heap top element
|
||||
func (h *intHeap) Top() any {
|
||||
return (*h)[0]
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
// File: heap_test.go
|
||||
// Created Time: 2023-01-12
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_heap
|
||||
|
||||
import (
|
||||
"container/heap"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
func testPush(h *intHeap, val int) {
|
||||
// Call heap.Interface function to add element
|
||||
heap.Push(h, val)
|
||||
fmt.Printf("\nAfter element %d pushes to heap \n", val)
|
||||
PrintHeap(*h)
|
||||
}
|
||||
|
||||
func testPop(h *intHeap) {
|
||||
// Call heap.Interface function to remove element
|
||||
val := heap.Pop(h)
|
||||
fmt.Printf("\nAfter heap top element %d pops from heap \n", val)
|
||||
PrintHeap(*h)
|
||||
}
|
||||
|
||||
func TestHeap(t *testing.T) {
|
||||
/* Initialize heap */
|
||||
// Consider negating the elements before entering the heap, which can reverse the size relationship, thus implementing max heap
|
||||
maxHeap := &intHeap{}
|
||||
heap.Init(maxHeap)
|
||||
/* Element enters heap */
|
||||
testPush(maxHeap, 1)
|
||||
testPush(maxHeap, 3)
|
||||
testPush(maxHeap, 2)
|
||||
testPush(maxHeap, 5)
|
||||
testPush(maxHeap, 4)
|
||||
|
||||
/* Check if heap is empty */
|
||||
top := maxHeap.Top()
|
||||
fmt.Printf("Heap top element is %d\n", top)
|
||||
|
||||
/* Time complexity is O(n), not O(nlogn) */
|
||||
testPop(maxHeap)
|
||||
testPop(maxHeap)
|
||||
testPop(maxHeap)
|
||||
testPop(maxHeap)
|
||||
testPop(maxHeap)
|
||||
|
||||
/* Get heap size */
|
||||
size := len(*maxHeap)
|
||||
fmt.Printf("Heap size is %d\n", size)
|
||||
|
||||
/* Check if heap is empty */
|
||||
isEmpty := len(*maxHeap) == 0
|
||||
fmt.Printf("Is heap empty %t\n", isEmpty)
|
||||
}
|
||||
|
||||
func TestMyHeap(t *testing.T) {
|
||||
/* Initialize heap */
|
||||
// Consider negating the elements before entering the heap, which can reverse the size relationship, thus implementing max heap
|
||||
maxHeap := newMaxHeap([]any{9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2})
|
||||
fmt.Printf("After input array and building heap\n")
|
||||
maxHeap.print()
|
||||
|
||||
/* Check if heap is empty */
|
||||
peek := maxHeap.peek()
|
||||
fmt.Printf("\nHeap top element is %d\n", peek)
|
||||
|
||||
/* Element enters heap */
|
||||
val := 7
|
||||
maxHeap.push(val)
|
||||
fmt.Printf("\nAfter element %d enters heap\n", val)
|
||||
maxHeap.print()
|
||||
|
||||
/* Time complexity is O(n), not O(nlogn) */
|
||||
peek = maxHeap.pop()
|
||||
fmt.Printf("\nAfter heap top element %d exits heap\n", peek)
|
||||
maxHeap.print()
|
||||
|
||||
/* Get heap size */
|
||||
size := maxHeap.size()
|
||||
fmt.Printf("\nHeap element count is %d\n", size)
|
||||
|
||||
/* Check if heap is empty */
|
||||
isEmpty := maxHeap.isEmpty()
|
||||
fmt.Printf("\nIs heap empty %t\n", isEmpty)
|
||||
}
|
||||
|
||||
func TestTopKHeap(t *testing.T) {
|
||||
/* Initialize heap */
|
||||
// Consider negating the elements before entering the heap, which can reverse the size relationship, thus implementing max heap
|
||||
nums := []int{1, 7, 6, 3, 2}
|
||||
k := 3
|
||||
res := topKHeap(nums, k)
|
||||
fmt.Printf("The largest " + strconv.Itoa(k) + " elements are")
|
||||
PrintHeap(*res)
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
// File: my_heap.go
|
||||
// Created Time: 2023-01-12
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_heap
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
type maxHeap struct {
|
||||
// Use slice instead of array to avoid expansion issues
|
||||
data []any
|
||||
}
|
||||
|
||||
/* Constructor, build empty heap */
|
||||
func newHeap() *maxHeap {
|
||||
return &maxHeap{
|
||||
data: make([]any, 0),
|
||||
}
|
||||
}
|
||||
|
||||
/* Constructor, build heap from slice */
|
||||
func newMaxHeap(nums []any) *maxHeap {
|
||||
// Add list elements to heap as is
|
||||
h := &maxHeap{data: nums}
|
||||
for i := h.parent(len(h.data) - 1); i >= 0; i-- {
|
||||
// Heapify all nodes except leaf nodes
|
||||
h.siftDown(i)
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
/* Get index of left child node */
|
||||
func (h *maxHeap) left(i int) int {
|
||||
return 2*i + 1
|
||||
}
|
||||
|
||||
/* Get index of right child node */
|
||||
func (h *maxHeap) right(i int) int {
|
||||
return 2*i + 2
|
||||
}
|
||||
|
||||
/* Get index of parent node */
|
||||
func (h *maxHeap) parent(i int) int {
|
||||
// Floor division
|
||||
return (i - 1) / 2
|
||||
}
|
||||
|
||||
/* Swap elements */
|
||||
func (h *maxHeap) swap(i, j int) {
|
||||
h.data[i], h.data[j] = h.data[j], h.data[i]
|
||||
}
|
||||
|
||||
/* Get heap size */
|
||||
func (h *maxHeap) size() int {
|
||||
return len(h.data)
|
||||
}
|
||||
|
||||
/* Check if heap is empty */
|
||||
func (h *maxHeap) isEmpty() bool {
|
||||
return len(h.data) == 0
|
||||
}
|
||||
|
||||
/* Access top element */
|
||||
func (h *maxHeap) peek() any {
|
||||
return h.data[0]
|
||||
}
|
||||
|
||||
/* Element enters heap */
|
||||
func (h *maxHeap) push(val any) {
|
||||
// Add node
|
||||
h.data = append(h.data, val)
|
||||
// Heapify from bottom to top
|
||||
h.siftUp(len(h.data) - 1)
|
||||
}
|
||||
|
||||
/* Starting from node i, heapify from bottom to top */
|
||||
func (h *maxHeap) siftUp(i int) {
|
||||
for true {
|
||||
// Get parent node of node i
|
||||
p := h.parent(i)
|
||||
// When "crossing root node" or "node needs no repair", end heapify
|
||||
if p < 0 || h.data[i].(int) <= h.data[p].(int) {
|
||||
break
|
||||
}
|
||||
// Swap two nodes
|
||||
h.swap(i, p)
|
||||
// Loop upward heapify
|
||||
i = p
|
||||
}
|
||||
}
|
||||
|
||||
/* Element exits heap */
|
||||
func (h *maxHeap) pop() any {
|
||||
// Handle empty case
|
||||
if h.isEmpty() {
|
||||
fmt.Println("error")
|
||||
return nil
|
||||
}
|
||||
// Delete node
|
||||
h.swap(0, h.size()-1)
|
||||
// Remove node
|
||||
val := h.data[len(h.data)-1]
|
||||
h.data = h.data[:len(h.data)-1]
|
||||
// Return top element
|
||||
h.siftDown(0)
|
||||
|
||||
// Return heap top element
|
||||
return val
|
||||
}
|
||||
|
||||
/* Starting from node i, heapify from top to bottom */
|
||||
func (h *maxHeap) siftDown(i int) {
|
||||
for true {
|
||||
// Find node with maximum value among nodes i, l, r, denoted as max
|
||||
l, r, max := h.left(i), h.right(i), i
|
||||
if l < h.size() && h.data[l].(int) > h.data[max].(int) {
|
||||
max = l
|
||||
}
|
||||
if r < h.size() && h.data[r].(int) > h.data[max].(int) {
|
||||
max = r
|
||||
}
|
||||
// Swap two nodes
|
||||
if max == i {
|
||||
break
|
||||
}
|
||||
// Swap two nodes
|
||||
h.swap(i, max)
|
||||
// Loop downwards heapification
|
||||
i = max
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
func (h *maxHeap) print() {
|
||||
PrintHeap(h.data)
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// File: top_k.go
|
||||
// Created Time: 2023-06-24
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_heap
|
||||
|
||||
import "container/heap"
|
||||
|
||||
type minHeap []any
|
||||
|
||||
func (h *minHeap) Len() int { return len(*h) }
|
||||
func (h *minHeap) Less(i, j int) bool { return (*h)[i].(int) < (*h)[j].(int) }
|
||||
func (h *minHeap) Swap(i, j int) { (*h)[i], (*h)[j] = (*h)[j], (*h)[i] }
|
||||
|
||||
// Push method of heap.Interface, implements pushing element to heap
|
||||
func (h *minHeap) Push(x any) {
|
||||
*h = append(*h, x.(int))
|
||||
}
|
||||
|
||||
// Pop method of heap.Interface, implements popping heap top element
|
||||
func (h *minHeap) Pop() any {
|
||||
// Element to be popped is stored at the end
|
||||
last := (*h)[len(*h)-1]
|
||||
*h = (*h)[:len(*h)-1]
|
||||
return last
|
||||
}
|
||||
|
||||
// Top gets heap top element
|
||||
func (h *minHeap) Top() any {
|
||||
return (*h)[0]
|
||||
}
|
||||
|
||||
/* Find the largest k elements in array based on heap */
|
||||
func topKHeap(nums []int, k int) *minHeap {
|
||||
// Python's heapq module implements min heap by default
|
||||
h := &minHeap{}
|
||||
heap.Init(h)
|
||||
// Enter the first k elements of array into heap
|
||||
for i := 0; i < k; i++ {
|
||||
heap.Push(h, nums[i])
|
||||
}
|
||||
// Starting from the (k+1)th element, maintain heap length as k
|
||||
for i := k; i < len(nums); i++ {
|
||||
// If current element is greater than top element, top element exits heap, current element enters heap
|
||||
if nums[i] > h.Top().(int) {
|
||||
heap.Pop(h)
|
||||
heap.Push(h, nums[i])
|
||||
}
|
||||
}
|
||||
return h
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// File: binary_search.go
|
||||
// Created Time: 2022-12-05
|
||||
// Author: Slone123c (274325721@qq.com)
|
||||
|
||||
package chapter_searching
|
||||
|
||||
/* Binary search (closed interval on both sides) */
|
||||
func binarySearch(nums []int, target int) int {
|
||||
// Initialize closed interval [0, n-1], i.e., i, j point to the first and last elements of the array
|
||||
i, j := 0, len(nums)-1
|
||||
// Loop, exit when the search interval is empty (empty when i > j)
|
||||
for i <= j {
|
||||
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) */
|
||||
func binarySearchLCRO(nums []int, target int) int {
|
||||
// Initialize left-closed right-open interval [0, n), i.e., i, j point to the first element and last element+1
|
||||
i, j := 0, len(nums)
|
||||
// Loop, exit when the search interval is empty (empty when i = j)
|
||||
for i < j {
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// File: binary_search_edge.go
|
||||
// Created Time: 2023-08-23
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_searching
|
||||
|
||||
/* Binary search for the leftmost target */
|
||||
func binarySearchLeftEdge(nums []int, target int) int {
|
||||
// Equivalent to finding the insertion point of target
|
||||
i := binarySearchInsertion(nums, target)
|
||||
// Target not found, return -1
|
||||
if i == len(nums) || nums[i] != target {
|
||||
return -1
|
||||
}
|
||||
// Found target, return index i
|
||||
return i
|
||||
}
|
||||
|
||||
/* Binary search for the rightmost target */
|
||||
func binarySearchRightEdge(nums []int, target int) int {
|
||||
// Convert to finding the leftmost target + 1
|
||||
i := binarySearchInsertion(nums, target+1)
|
||||
// j points to the rightmost target, i points to the first element greater than target
|
||||
j := i - 1
|
||||
// Target not found, return -1
|
||||
if j == -1 || nums[j] != target {
|
||||
return -1
|
||||
}
|
||||
// Found target, return index j
|
||||
return j
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
// File: binary_search_insertion.go
|
||||
// Created Time: 2023-08-23
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_searching
|
||||
|
||||
/* Binary search for insertion point (no duplicate elements) */
|
||||
func binarySearchInsertionSimple(nums []int, target int) int {
|
||||
// Initialize closed interval [0, n-1]
|
||||
i, j := 0, len(nums)-1
|
||||
for i <= j {
|
||||
// Calculate the midpoint index m
|
||||
m := i + (j-i)/2
|
||||
if nums[m] < target {
|
||||
// target is in the interval [m+1, j]
|
||||
i = m + 1
|
||||
} else if nums[m] > target {
|
||||
// target is in the interval [i, m-1]
|
||||
j = m - 1
|
||||
} else {
|
||||
// Found target, return insertion point m
|
||||
return m
|
||||
}
|
||||
}
|
||||
// Target not found, return insertion point i
|
||||
return i
|
||||
}
|
||||
|
||||
/* Binary search for insertion point (with duplicate elements) */
|
||||
func binarySearchInsertion(nums []int, target int) int {
|
||||
// Initialize closed interval [0, n-1]
|
||||
i, j := 0, len(nums)-1
|
||||
for i <= j {
|
||||
// Calculate the midpoint index m
|
||||
m := i + (j-i)/2
|
||||
if nums[m] < target {
|
||||
// target is in the interval [m+1, j]
|
||||
i = m + 1
|
||||
} else if nums[m] > target {
|
||||
// target is in the interval [i, m-1]
|
||||
j = m - 1
|
||||
} else {
|
||||
// The first element less than target is in the interval [i, m-1]
|
||||
j = m - 1
|
||||
}
|
||||
}
|
||||
// Return insertion point i
|
||||
return i
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// File: binary_search_test.go
|
||||
// Created Time: 2022-12-05
|
||||
// Author: Slone123c (274325721@qq.com)
|
||||
|
||||
package chapter_searching
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBinarySearch(t *testing.T) {
|
||||
var (
|
||||
target = 6
|
||||
nums = []int{1, 3, 6, 8, 12, 15, 23, 26, 31, 35}
|
||||
expected = 2
|
||||
)
|
||||
// Perform binary search in array
|
||||
actual := binarySearch(nums, target)
|
||||
fmt.Println("Index of target element 6 =", actual)
|
||||
if actual != expected {
|
||||
t.Errorf("Index of target element 6 = %d, should be %d", actual, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBinarySearchEdge(t *testing.T) {
|
||||
// Array with duplicate elements
|
||||
nums := []int{1, 3, 6, 8, 12, 15, 23, 26, 31, 35}
|
||||
fmt.Println("\nArray nums = ", nums)
|
||||
|
||||
// Binary search left and right boundaries
|
||||
for _, target := range []int{6, 7} {
|
||||
index := binarySearchLeftEdge(nums, target)
|
||||
fmt.Println("Leftmost element", target, " index is", index)
|
||||
|
||||
index = binarySearchRightEdge(nums, target)
|
||||
fmt.Println("Rightmost element", target, " index is", index)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBinarySearchInsertion(t *testing.T) {
|
||||
// Array without duplicate elements
|
||||
nums := []int{1, 3, 6, 8, 12, 15, 23, 26, 31, 35}
|
||||
fmt.Println("Array nums =", nums)
|
||||
|
||||
// Binary search for insertion point
|
||||
for _, target := range []int{6, 9} {
|
||||
index := binarySearchInsertionSimple(nums, target)
|
||||
fmt.Println("Element", target, " insertion point index is", index)
|
||||
}
|
||||
|
||||
// Array with duplicate elements
|
||||
nums = []int{1, 3, 6, 6, 6, 6, 6, 10, 12, 15}
|
||||
fmt.Println("\nArray nums =", nums)
|
||||
|
||||
// Binary search for insertion point
|
||||
for _, target := range []int{2, 6, 20} {
|
||||
index := binarySearchInsertion(nums, target)
|
||||
fmt.Println("Element", target, " insertion point index is", index)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// File: hashing_search.go
|
||||
// Created Time: 2022-12-12
|
||||
// Author: Slone123c (274325721@qq.com)
|
||||
|
||||
package chapter_searching
|
||||
|
||||
import . "github.com/krahets/hello-algo/pkg"
|
||||
|
||||
/* Hash search (array) */
|
||||
func hashingSearchArray(m map[int]int, target int) int {
|
||||
// Hash table's key: target element, value: index
|
||||
// If this key does not exist in the hash table, return -1
|
||||
if index, ok := m[target]; ok {
|
||||
return index
|
||||
} else {
|
||||
return -1
|
||||
}
|
||||
}
|
||||
|
||||
/* Hash search (linked list) */
|
||||
func hashingSearchLinkedList(m map[int]*ListNode, target int) *ListNode {
|
||||
// Hash table key: target node value, value: node object
|
||||
// Return nil if key does not exist in hash table
|
||||
if node, ok := m[target]; ok {
|
||||
return node
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// File: hashing_search_test.go
|
||||
// Created Time: 2022-12-12
|
||||
// Author: Slone123c (274325721@qq.com)
|
||||
|
||||
package chapter_searching
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
func TestHashingSearch(t *testing.T) {
|
||||
target := 3
|
||||
/* Hash search (array) */
|
||||
nums := []int{1, 5, 3, 2, 4, 7, 5, 9, 10, 8}
|
||||
// Initialize hash table
|
||||
m := make(map[int]int)
|
||||
for i := 0; i < len(nums); i++ {
|
||||
m[nums[i]] = i
|
||||
}
|
||||
index := hashingSearchArray(m, target)
|
||||
fmt.Println("Index of target element 3 = ", index)
|
||||
|
||||
/* Hash search (linked list) */
|
||||
head := ArrayToLinkedList(nums)
|
||||
// Initialize hash table
|
||||
m1 := make(map[int]*ListNode)
|
||||
for head != nil {
|
||||
m1[head.Val] = head
|
||||
head = head.Next
|
||||
}
|
||||
node := hashingSearchLinkedList(m1, target)
|
||||
fmt.Println("Node object corresponding to target node value 3 is ", node)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// File: linear_search.go
|
||||
// Created Time: 2022-11-25
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_searching
|
||||
|
||||
import (
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
/* Linear search (array) */
|
||||
func linearSearchArray(nums []int, target int) int {
|
||||
// Traverse array
|
||||
for i := 0; i < len(nums); 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) */
|
||||
func linearSearchLinkedList(node *ListNode, target int) *ListNode {
|
||||
// Traverse the linked list
|
||||
for node != nil {
|
||||
// Found the target node, return it
|
||||
if node.Val == target {
|
||||
return node
|
||||
}
|
||||
node = node.Next
|
||||
}
|
||||
// Target element not found, return nil
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// File: linear_search_test.go
|
||||
// Created Time: 2022-11-25
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_searching
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
func TestLinearSearch(t *testing.T) {
|
||||
target := 3
|
||||
nums := []int{1, 5, 3, 2, 4, 7, 5, 9, 10, 8}
|
||||
|
||||
// Perform linear search in array
|
||||
index := linearSearchArray(nums, target)
|
||||
fmt.Println("Index of target element 3 =", index)
|
||||
|
||||
// Perform linear search in linked list
|
||||
head := ArrayToLinkedList(nums)
|
||||
node := linearSearchLinkedList(head, target)
|
||||
fmt.Println("Node object with target value 3 is", node)
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// File: two_sum.go
|
||||
// Created Time: 2022-11-25
|
||||
// Author: reanon (793584285@qq.com)
|
||||
|
||||
package chapter_searching
|
||||
|
||||
/* Method 1: Brute force enumeration */
|
||||
func twoSumBruteForce(nums []int, target int) []int {
|
||||
size := len(nums)
|
||||
// Two nested loops, time complexity is O(n^2)
|
||||
for i := 0; i < size-1; i++ {
|
||||
for j := i + 1; j < size; j++ {
|
||||
if nums[i]+nums[j] == target {
|
||||
return []int{i, j}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/* Method 2: Auxiliary hash table */
|
||||
func twoSumHashTable(nums []int, target int) []int {
|
||||
// Auxiliary hash table, space complexity is O(n)
|
||||
hashTable := map[int]int{}
|
||||
// Single loop, time complexity is O(n)
|
||||
for idx, val := range nums {
|
||||
if preIdx, ok := hashTable[target-val]; ok {
|
||||
return []int{preIdx, idx}
|
||||
}
|
||||
hashTable[val] = idx
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// File: two_sum_test.go
|
||||
// Created Time: 2022-11-25
|
||||
// Author: reanon (793584285@qq.com)
|
||||
|
||||
package chapter_searching
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTwoSum(t *testing.T) {
|
||||
// ======= Test Case =======
|
||||
nums := []int{2, 7, 11, 15}
|
||||
target := 13
|
||||
|
||||
// ====== Driver Code ======
|
||||
// Method 1: Brute-force approach
|
||||
res := twoSumBruteForce(nums, target)
|
||||
fmt.Println("Method 1 res =", res)
|
||||
// Method 2: Hash table
|
||||
res = twoSumHashTable(nums, target)
|
||||
fmt.Println("Method 2 res =", res)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// File: bubble_sort.go
|
||||
// Created Time: 2022-12-06
|
||||
// Author: Slone123c (274325721@qq.com)
|
||||
|
||||
package chapter_sorting
|
||||
|
||||
/* Bubble sort */
|
||||
func bubbleSort(nums []int) {
|
||||
// Outer loop: unsorted range is [0, i]
|
||||
for i := len(nums) - 1; i > 0; i-- {
|
||||
// Inner loop: swap the largest element in the unsorted range [0, i] to the rightmost end of that range
|
||||
for j := 0; j < i; j++ {
|
||||
if nums[j] > nums[j+1] {
|
||||
// Swap nums[j] and nums[j + 1]
|
||||
nums[j], nums[j+1] = nums[j+1], nums[j]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Bubble sort (flag optimization) */
|
||||
func bubbleSortWithFlag(nums []int) {
|
||||
// Outer loop: unsorted range is [0, i]
|
||||
for i := len(nums) - 1; i > 0; i-- {
|
||||
flag := false // Initialize flag
|
||||
// Inner loop: swap the largest element in the unsorted range [0, i] to the rightmost end of that range
|
||||
for j := 0; j < i; j++ {
|
||||
if nums[j] > nums[j+1] {
|
||||
// Swap nums[j] and nums[j + 1]
|
||||
nums[j], nums[j+1] = nums[j+1], nums[j]
|
||||
flag = true // Record element swap
|
||||
}
|
||||
}
|
||||
if flag == false { // No elements were swapped in this round of "bubbling", exit directly
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// File: bubble_sort_test.go
|
||||
// Created Time: 2022-12-06
|
||||
// Author: Slone123c (274325721@qq.com)
|
||||
|
||||
package chapter_sorting
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBubbleSort(t *testing.T) {
|
||||
nums := []int{4, 1, 3, 1, 5, 2}
|
||||
bubbleSort(nums)
|
||||
fmt.Println("After bubble sort completes, nums = ", nums)
|
||||
|
||||
nums1 := []int{4, 1, 3, 1, 5, 2}
|
||||
bubbleSortWithFlag(nums1)
|
||||
fmt.Println("After bubble sort completes, nums1 = ", nums1)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// File: bucket_sort.go
|
||||
// Created Time: 2023-03-27
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_sorting
|
||||
|
||||
import "sort"
|
||||
|
||||
/* Bucket sort */
|
||||
func bucketSort(nums []float64) {
|
||||
// Initialize k = n/2 buckets, expected to allocate 2 elements per bucket
|
||||
k := len(nums) / 2
|
||||
buckets := make([][]float64, k)
|
||||
for i := 0; i < k; i++ {
|
||||
buckets[i] = make([]float64, 0)
|
||||
}
|
||||
// 1. Distribute array elements into various buckets
|
||||
for _, num := range nums {
|
||||
// Input data range is [0, 1), use num * k to map to index range [0, k-1]
|
||||
i := int(num * float64(k))
|
||||
// Add num to bucket i
|
||||
buckets[i] = append(buckets[i], num)
|
||||
}
|
||||
// 2. Sort each bucket
|
||||
for i := 0; i < k; i++ {
|
||||
// Use built-in slice sorting function, can also be replaced with other sorting algorithms
|
||||
sort.Float64s(buckets[i])
|
||||
}
|
||||
// 3. Traverse buckets to merge results
|
||||
i := 0
|
||||
for _, bucket := range buckets {
|
||||
for _, num := range bucket {
|
||||
nums[i] = num
|
||||
i++
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// File: bucket_sort_test.go
|
||||
// Created Time: 2023-03-27
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_sorting
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBucketSort(t *testing.T) {
|
||||
// Assume input data is floating point, interval [0, 1)
|
||||
nums := []float64{0.49, 0.96, 0.82, 0.09, 0.57, 0.43, 0.91, 0.75, 0.15, 0.37}
|
||||
bucketSort(nums)
|
||||
fmt.Println("After bucket sort completes, nums = ", nums)
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// File: counting_sort.go
|
||||
// Created Time: 2023-03-20
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_sorting
|
||||
|
||||
type CountingSort struct{}
|
||||
|
||||
/* Counting sort */
|
||||
// Simple implementation, cannot be used for sorting objects
|
||||
func countingSortNaive(nums []int) {
|
||||
// 1. Count the maximum element m in the array
|
||||
m := 0
|
||||
for _, num := range nums {
|
||||
if num > m {
|
||||
m = num
|
||||
}
|
||||
}
|
||||
// 2. Count the occurrence of each number
|
||||
// counter[num] represents the occurrence of num
|
||||
counter := make([]int, m+1)
|
||||
for _, num := range nums {
|
||||
counter[num]++
|
||||
}
|
||||
// 3. Traverse counter, filling each element back into the original array nums
|
||||
for i, num := 0, 0; num < m+1; num++ {
|
||||
for j := 0; j < counter[num]; j++ {
|
||||
nums[i] = num
|
||||
i++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Counting sort */
|
||||
// Complete implementation, can sort objects and is a stable sort
|
||||
func countingSort(nums []int) {
|
||||
// 1. Count the maximum element m in the array
|
||||
m := 0
|
||||
for _, num := range nums {
|
||||
if num > m {
|
||||
m = num
|
||||
}
|
||||
}
|
||||
// 2. Count the occurrence of each number
|
||||
// counter[num] represents the occurrence of num
|
||||
counter := make([]int, m+1)
|
||||
for _, num := range nums {
|
||||
counter[num]++
|
||||
}
|
||||
// 3. Calculate the prefix sum of counter, converting "occurrence count" to "tail index"
|
||||
// counter[num]-1 is the last index where num appears in res
|
||||
for 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
|
||||
n := len(nums)
|
||||
res := make([]int, n)
|
||||
for i := n - 1; i >= 0; i-- {
|
||||
num := nums[i]
|
||||
// Place num at the corresponding index
|
||||
res[counter[num]-1] = num
|
||||
// Decrement the prefix sum by 1, getting the next index to place num
|
||||
counter[num]--
|
||||
}
|
||||
// Use result array res to overwrite the original array nums
|
||||
copy(nums, res)
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// File: counting_sort_test.go
|
||||
// Created Time: 2023-03-20
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_sorting
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCountingSort(t *testing.T) {
|
||||
nums := []int{1, 0, 1, 2, 0, 4, 0, 2, 2, 4}
|
||||
countingSortNaive(nums)
|
||||
fmt.Println("After counting sort (cannot sort objects) completes, nums = ", nums)
|
||||
|
||||
nums1 := []int{1, 0, 1, 2, 0, 4, 0, 2, 2, 4}
|
||||
countingSort(nums1)
|
||||
fmt.Println("After counting sort completes, nums1 = ", nums1)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// File: heap_sort.go
|
||||
// Created Time: 2023-05-29
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_sorting
|
||||
|
||||
/* Heap length is n, start heapifying node i, from top to bottom */
|
||||
func siftDown(nums *[]int, n, i int) {
|
||||
for true {
|
||||
// If node i is largest or indices l, r are out of bounds, no need to continue heapify, break
|
||||
l := 2*i + 1
|
||||
r := 2*i + 2
|
||||
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
|
||||
(*nums)[i], (*nums)[ma] = (*nums)[ma], (*nums)[i]
|
||||
// Loop downwards heapification
|
||||
i = ma
|
||||
}
|
||||
}
|
||||
|
||||
/* Heap sort */
|
||||
func heapSort(nums *[]int) {
|
||||
// Build heap operation: heapify all nodes except leaves
|
||||
for i := len(*nums)/2 - 1; i >= 0; i-- {
|
||||
siftDown(nums, len(*nums), i)
|
||||
}
|
||||
// Extract the largest element from the heap and repeat for n-1 rounds
|
||||
for i := len(*nums) - 1; i > 0; i-- {
|
||||
// Delete node
|
||||
(*nums)[0], (*nums)[i] = (*nums)[i], (*nums)[0]
|
||||
// Start heapifying the root node, from top to bottom
|
||||
siftDown(nums, i, 0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// File: heap_sort_test.go
|
||||
// Created Time: 2023-05-29
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_sorting
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHeapSort(t *testing.T) {
|
||||
nums := []int{4, 1, 3, 1, 5, 2}
|
||||
heapSort(&nums)
|
||||
fmt.Println("After heap sort completes, nums = ", nums)
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// File: insertion_sort.go
|
||||
// Created Time: 2022-12-12
|
||||
// Author: msk397 (machangxinq@gmail.com)
|
||||
|
||||
package chapter_sorting
|
||||
|
||||
/* Insertion sort */
|
||||
func insertionSort(nums []int) {
|
||||
// Outer loop: sorted interval is [0, i-1]
|
||||
for i := 1; i < len(nums); i++ {
|
||||
base := nums[i]
|
||||
j := i - 1
|
||||
// Inner loop: insert base into the correct position within the sorted interval [0, i-1]
|
||||
for 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
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user