mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-15 16:36:06 +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,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]
|
||||
}
|
||||
Reference in New Issue
Block a user