mirror of
https://github.com/krahets/hello-algo.git
synced 2026-05-11 11:07:14 +08: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,44 @@
|
||||
/**
|
||||
* File: climbing_stairs_backtrack.swift
|
||||
* Created Time: 2023-07-15
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Backtracking */
|
||||
func backtrack(choices: [Int], state: Int, n: Int, res: inout [Int]) {
|
||||
// When climbing to the n-th stair, add 1 to the solution count
|
||||
if state == n {
|
||||
res[0] += 1
|
||||
}
|
||||
// Traverse all choices
|
||||
for choice in choices {
|
||||
// Pruning: not allowed to go beyond the n-th stair
|
||||
if state + choice > n {
|
||||
continue
|
||||
}
|
||||
// Attempt: make choice, update state
|
||||
backtrack(choices: choices, state: state + choice, n: n, res: &res)
|
||||
// Backtrack
|
||||
}
|
||||
}
|
||||
|
||||
/* Climbing stairs: Backtracking */
|
||||
func climbingStairsBacktrack(n: Int) -> Int {
|
||||
let choices = [1, 2] // Can choose to climb up 1 or 2 stairs
|
||||
let state = 0 // Start climbing from the 0-th stair
|
||||
var res: [Int] = []
|
||||
res.append(0) // Use res[0] to record the solution count
|
||||
backtrack(choices: choices, state: state, n: n, res: &res)
|
||||
return res[0]
|
||||
}
|
||||
|
||||
@main
|
||||
enum ClimbingStairsBacktrack {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let n = 9
|
||||
|
||||
let res = climbingStairsBacktrack(n: n)
|
||||
print("Climbing \(n) stairs has \(res) solutions")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* File: climbing_stairs_constraint_dp.swift
|
||||
* Created Time: 2023-07-15
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* 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
|
||||
var dp = Array(repeating: Array(repeating: 0, count: 3), count: 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 in 3 ... n {
|
||||
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]
|
||||
}
|
||||
|
||||
@main
|
||||
enum ClimbingStairsConstraintDP {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let n = 9
|
||||
|
||||
let res = climbingStairsConstraintDP(n: n)
|
||||
print("Climbing \(n) stairs has \(res) solutions")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* File: climbing_stairs_dfs.swift
|
||||
* Created Time: 2023-07-15
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* 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]
|
||||
let count = dfs(i: i - 1) + dfs(i: i - 2)
|
||||
return count
|
||||
}
|
||||
|
||||
/* Climbing stairs: Search */
|
||||
func climbingStairsDFS(n: Int) -> Int {
|
||||
dfs(i: n)
|
||||
}
|
||||
|
||||
@main
|
||||
enum ClimbingStairsDFS {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let n = 9
|
||||
|
||||
let res = climbingStairsDFS(n: n)
|
||||
print("Climbing \(n) stairs has \(res) solutions")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* File: climbing_stairs_dfs_mem.swift
|
||||
* Created Time: 2023-07-15
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Memoization search */
|
||||
func dfs(i: Int, mem: inout [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]
|
||||
let count = dfs(i: i - 1, mem: &mem) + dfs(i: i - 2, mem: &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
|
||||
var mem = Array(repeating: -1, count: n + 1)
|
||||
return dfs(i: n, mem: &mem)
|
||||
}
|
||||
|
||||
@main
|
||||
enum ClimbingStairsDFSMem {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let n = 9
|
||||
|
||||
let res = climbingStairsDFSMem(n: n)
|
||||
print("Climbing \(n) stairs has \(res) solutions")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* File: climbing_stairs_dp.swift
|
||||
* Created Time: 2023-07-15
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* 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
|
||||
var dp = Array(repeating: 0, count: 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 in 3 ... n {
|
||||
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
|
||||
}
|
||||
var a = 1
|
||||
var b = 2
|
||||
for _ in 3 ... n {
|
||||
(a, b) = (b, a + b)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
@main
|
||||
enum ClimbingStairsDP {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let n = 9
|
||||
|
||||
var res = climbingStairsDP(n: n)
|
||||
print("Climbing \(n) stairs has \(res) solutions")
|
||||
|
||||
res = climbingStairsDPComp(n: n)
|
||||
print("Climbing \(n) stairs has \(res) solutions")
|
||||
}
|
||||
}
|
||||
69
en/codes/swift/chapter_dynamic_programming/coin_change.swift
Normal file
69
en/codes/swift/chapter_dynamic_programming/coin_change.swift
Normal file
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* File: coin_change.swift
|
||||
* Created Time: 2023-07-15
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Coin change: Dynamic programming */
|
||||
func coinChangeDP(coins: [Int], amt: Int) -> Int {
|
||||
let n = coins.count
|
||||
let MAX = amt + 1
|
||||
// Initialize dp table
|
||||
var dp = Array(repeating: Array(repeating: 0, count: amt + 1), count: n + 1)
|
||||
// State transition: first row and first column
|
||||
for a in 1 ... amt {
|
||||
dp[0][a] = MAX
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
for i in 1 ... n {
|
||||
for a in 1 ... amt {
|
||||
if coins[i - 1] > a {
|
||||
// If exceeds target amount, don't select coin i
|
||||
dp[i][a] = dp[i - 1][a]
|
||||
} else {
|
||||
// The smaller value between not selecting and selecting coin i
|
||||
dp[i][a] = min(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][amt] != MAX ? dp[n][amt] : -1
|
||||
}
|
||||
|
||||
/* Coin change: Space-optimized dynamic programming */
|
||||
func coinChangeDPComp(coins: [Int], amt: Int) -> Int {
|
||||
let n = coins.count
|
||||
let MAX = amt + 1
|
||||
// Initialize dp table
|
||||
var dp = Array(repeating: MAX, count: amt + 1)
|
||||
dp[0] = 0
|
||||
// State transition
|
||||
for i in 1 ... n {
|
||||
for a in 1 ... amt {
|
||||
if coins[i - 1] > a {
|
||||
// If exceeds target amount, don't select coin i
|
||||
dp[a] = dp[a]
|
||||
} else {
|
||||
// The smaller value between not selecting and selecting coin i
|
||||
dp[a] = min(dp[a], dp[a - coins[i - 1]] + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[amt] != MAX ? dp[amt] : -1
|
||||
}
|
||||
|
||||
@main
|
||||
enum CoinChange {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let coins = [1, 2, 5]
|
||||
let amt = 4
|
||||
|
||||
// Dynamic programming
|
||||
var res = coinChangeDP(coins: coins, amt: amt)
|
||||
print("Minimum coins needed to make target amount is \(res)")
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = coinChangeDPComp(coins: coins, amt: amt)
|
||||
print("Minimum coins needed to make target amount is \(res)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* File: coin_change_ii.swift
|
||||
* Created Time: 2023-07-16
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Coin change II: Dynamic programming */
|
||||
func coinChangeIIDP(coins: [Int], amt: Int) -> Int {
|
||||
let n = coins.count
|
||||
// Initialize dp table
|
||||
var dp = Array(repeating: Array(repeating: 0, count: amt + 1), count: n + 1)
|
||||
// Initialize first column
|
||||
for i in 0 ... n {
|
||||
dp[i][0] = 1
|
||||
}
|
||||
// State transition
|
||||
for i in 1 ... n {
|
||||
for a in 1 ... amt {
|
||||
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 {
|
||||
let n = coins.count
|
||||
// Initialize dp table
|
||||
var dp = Array(repeating: 0, count: amt + 1)
|
||||
dp[0] = 1
|
||||
// State transition
|
||||
for i in 1 ... n {
|
||||
for a in 1 ... amt {
|
||||
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]
|
||||
}
|
||||
|
||||
@main
|
||||
enum CoinChangeII {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let coins = [1, 2, 5]
|
||||
let amt = 5
|
||||
|
||||
// Dynamic programming
|
||||
var res = coinChangeIIDP(coins: coins, amt: amt)
|
||||
print("Number of coin combinations to make target amount is \(res)")
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = coinChangeIIDPComp(coins: coins, amt: amt)
|
||||
print("Number of coin combinations to make target amount is \(res)")
|
||||
}
|
||||
}
|
||||
147
en/codes/swift/chapter_dynamic_programming/edit_distance.swift
Normal file
147
en/codes/swift/chapter_dynamic_programming/edit_distance.swift
Normal file
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* File: edit_distance.swift
|
||||
* Created Time: 2023-07-16
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* 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.utf8CString[i - 1] == t.utf8CString[j - 1] {
|
||||
return editDistanceDFS(s: s, t: t, i: i - 1, j: j - 1)
|
||||
}
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
let insert = editDistanceDFS(s: s, t: t, i: i, j: j - 1)
|
||||
let delete = editDistanceDFS(s: s, t: t, i: i - 1, j: j)
|
||||
let replace = editDistanceDFS(s: s, t: t, i: i - 1, j: j - 1)
|
||||
// Return minimum edit steps
|
||||
return min(min(insert, delete), replace) + 1
|
||||
}
|
||||
|
||||
/* Edit distance: Memoization search */
|
||||
func editDistanceDFSMem(s: String, t: String, mem: inout [[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.utf8CString[i - 1] == t.utf8CString[j - 1] {
|
||||
return editDistanceDFS(s: s, t: t, i: i - 1, j: j - 1)
|
||||
}
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
let insert = editDistanceDFS(s: s, t: t, i: i, j: j - 1)
|
||||
let delete = editDistanceDFS(s: s, t: t, i: i - 1, j: j)
|
||||
let replace = editDistanceDFS(s: s, t: t, i: i - 1, j: j - 1)
|
||||
// Record and return minimum edit steps
|
||||
mem[i][j] = min(min(insert, delete), replace) + 1
|
||||
return mem[i][j]
|
||||
}
|
||||
|
||||
/* Edit distance: Dynamic programming */
|
||||
func editDistanceDP(s: String, t: String) -> Int {
|
||||
let n = s.utf8CString.count
|
||||
let m = t.utf8CString.count
|
||||
var dp = Array(repeating: Array(repeating: 0, count: m + 1), count: n + 1)
|
||||
// State transition: first row and first column
|
||||
for i in 1 ... n {
|
||||
dp[i][0] = i
|
||||
}
|
||||
for j in 1 ... m {
|
||||
dp[0][j] = j
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
for i in 1 ... n {
|
||||
for j in 1 ... m {
|
||||
if s.utf8CString[i - 1] == t.utf8CString[j - 1] {
|
||||
// If two characters are equal, skip both characters
|
||||
dp[i][j] = dp[i - 1][j - 1]
|
||||
} else {
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
dp[i][j] = min(min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][m]
|
||||
}
|
||||
|
||||
/* Edit distance: Space-optimized dynamic programming */
|
||||
func editDistanceDPComp(s: String, t: String) -> Int {
|
||||
let n = s.utf8CString.count
|
||||
let m = t.utf8CString.count
|
||||
var dp = Array(repeating: 0, count: m + 1)
|
||||
// State transition: first row
|
||||
for j in 1 ... m {
|
||||
dp[j] = j
|
||||
}
|
||||
// State transition: rest of the rows
|
||||
for i in 1 ... n {
|
||||
// State transition: first column
|
||||
var leftup = dp[0] // Temporarily store dp[i-1, j-1]
|
||||
dp[0] = i
|
||||
// State transition: rest of the columns
|
||||
for j in 1 ... m {
|
||||
let temp = dp[j]
|
||||
if s.utf8CString[i - 1] == t.utf8CString[j - 1] {
|
||||
// If two characters are equal, skip both characters
|
||||
dp[j] = leftup
|
||||
} else {
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
dp[j] = min(min(dp[j - 1], dp[j]), leftup) + 1
|
||||
}
|
||||
leftup = temp // Update for next round's dp[i-1, j-1]
|
||||
}
|
||||
}
|
||||
return dp[m]
|
||||
}
|
||||
|
||||
@main
|
||||
enum EditDistance {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let s = "bag"
|
||||
let t = "pack"
|
||||
let n = s.utf8CString.count
|
||||
let m = t.utf8CString.count
|
||||
|
||||
// Brute-force search
|
||||
var res = editDistanceDFS(s: s, t: t, i: n, j: m)
|
||||
print("Changing \(s) to \(t) requires minimum \(res) edits")
|
||||
|
||||
// Memoization search
|
||||
var mem = Array(repeating: Array(repeating: -1, count: m + 1), count: n + 1)
|
||||
res = editDistanceDFSMem(s: s, t: t, mem: &mem, i: n, j: m)
|
||||
print("Changing \(s) to \(t) requires minimum \(res) edits")
|
||||
|
||||
// Dynamic programming
|
||||
res = editDistanceDP(s: s, t: t)
|
||||
print("Changing \(s) to \(t) requires minimum \(res) edits")
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = editDistanceDPComp(s: s, t: t)
|
||||
print("Changing \(s) to \(t) requires minimum \(res) edits")
|
||||
}
|
||||
}
|
||||
110
en/codes/swift/chapter_dynamic_programming/knapsack.swift
Normal file
110
en/codes/swift/chapter_dynamic_programming/knapsack.swift
Normal file
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* File: knapsack.swift
|
||||
* Created Time: 2023-07-15
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* 0-1 knapsack: Brute-force search */
|
||||
func knapsackDFS(wgt: [Int], val: [Int], i: Int, 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: wgt, val: val, i: i - 1, c: c)
|
||||
}
|
||||
// Calculate the maximum value of not putting in and putting in item i
|
||||
let no = knapsackDFS(wgt: wgt, val: val, i: i - 1, c: c)
|
||||
let yes = knapsackDFS(wgt: wgt, val: val, i: i - 1, c: c - wgt[i - 1]) + val[i - 1]
|
||||
// Return the larger value of the two options
|
||||
return max(no, yes)
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Memoization search */
|
||||
func knapsackDFSMem(wgt: [Int], val: [Int], mem: inout [[Int]], i: Int, 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: wgt, val: val, mem: &mem, i: i - 1, c: c)
|
||||
}
|
||||
// Calculate the maximum value of not putting in and putting in item i
|
||||
let no = knapsackDFSMem(wgt: wgt, val: val, mem: &mem, i: i - 1, c: c)
|
||||
let yes = knapsackDFSMem(wgt: wgt, val: val, mem: &mem, i: i - 1, c: c - wgt[i - 1]) + val[i - 1]
|
||||
// Record and return the larger value of the two options
|
||||
mem[i][c] = max(no, yes)
|
||||
return mem[i][c]
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Dynamic programming */
|
||||
func knapsackDP(wgt: [Int], val: [Int], cap: Int) -> Int {
|
||||
let n = wgt.count
|
||||
// Initialize dp table
|
||||
var dp = Array(repeating: Array(repeating: 0, count: cap + 1), count: n + 1)
|
||||
// State transition
|
||||
for i in 1 ... n {
|
||||
for c in 1 ... cap {
|
||||
if wgt[i - 1] > c {
|
||||
// If exceeds knapsack capacity, don't select item i
|
||||
dp[i][c] = dp[i - 1][c]
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
dp[i][c] = max(dp[i - 1][c], dp[i - 1][c - wgt[i - 1]] + val[i - 1])
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][cap]
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Space-optimized dynamic programming */
|
||||
func knapsackDPComp(wgt: [Int], val: [Int], cap: Int) -> Int {
|
||||
let n = wgt.count
|
||||
// Initialize dp table
|
||||
var dp = Array(repeating: 0, count: cap + 1)
|
||||
// State transition
|
||||
for i in 1 ... n {
|
||||
// Traverse in reverse order
|
||||
for c in (1 ... cap).reversed() {
|
||||
if wgt[i - 1] <= c {
|
||||
// The larger value between not selecting and selecting item i
|
||||
dp[c] = max(dp[c], dp[c - wgt[i - 1]] + val[i - 1])
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap]
|
||||
}
|
||||
|
||||
@main
|
||||
enum Knapsack {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let wgt = [10, 20, 30, 40, 50]
|
||||
let val = [50, 120, 150, 210, 240]
|
||||
let cap = 50
|
||||
let n = wgt.count
|
||||
|
||||
// Brute-force search
|
||||
var res = knapsackDFS(wgt: wgt, val: val, i: n, c: cap)
|
||||
print("Maximum item value not exceeding knapsack capacity is \(res)")
|
||||
|
||||
// Memoization search
|
||||
var mem = Array(repeating: Array(repeating: -1, count: cap + 1), count: n + 1)
|
||||
res = knapsackDFSMem(wgt: wgt, val: val, mem: &mem, i: n, c: cap)
|
||||
print("Maximum item value not exceeding knapsack capacity is \(res)")
|
||||
|
||||
// Dynamic programming
|
||||
res = knapsackDP(wgt: wgt, val: val, cap: cap)
|
||||
print("Maximum item value not exceeding knapsack capacity is \(res)")
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = knapsackDPComp(wgt: wgt, val: val, cap: cap)
|
||||
print("Maximum item value not exceeding knapsack capacity is \(res)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* File: min_cost_climbing_stairs_dp.swift
|
||||
* Created Time: 2023-07-15
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Minimum cost climbing stairs: Dynamic programming */
|
||||
func minCostClimbingStairsDP(cost: [Int]) -> Int {
|
||||
let n = cost.count - 1
|
||||
if n == 1 || n == 2 {
|
||||
return cost[n]
|
||||
}
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
var dp = Array(repeating: 0, count: 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 in 3 ... n {
|
||||
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 {
|
||||
let n = cost.count - 1
|
||||
if n == 1 || n == 2 {
|
||||
return cost[n]
|
||||
}
|
||||
var (a, b) = (cost[1], cost[2])
|
||||
for i in 3 ... n {
|
||||
(a, b) = (b, min(a, b) + cost[i])
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
@main
|
||||
enum MinCostClimbingStairsDP {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let cost = [0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1]
|
||||
print("Input stair cost list is \(cost)")
|
||||
|
||||
var res = minCostClimbingStairsDP(cost: cost)
|
||||
print("Minimum cost to climb stairs is \(res)")
|
||||
|
||||
res = minCostClimbingStairsDPComp(cost: cost)
|
||||
print("Minimum cost to climb stairs is \(res)")
|
||||
}
|
||||
}
|
||||
123
en/codes/swift/chapter_dynamic_programming/min_path_sum.swift
Normal file
123
en/codes/swift/chapter_dynamic_programming/min_path_sum.swift
Normal file
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* File: min_path_sum.swift
|
||||
* Created Time: 2023-07-15
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Minimum path sum: Brute-force search */
|
||||
func minPathSumDFS(grid: [[Int]], i: Int, 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 .max
|
||||
}
|
||||
// Calculate the minimum path cost from top-left to (i-1, j) and (i, j-1)
|
||||
let up = minPathSumDFS(grid: grid, i: i - 1, j: j)
|
||||
let left = minPathSumDFS(grid: grid, i: i, j: j - 1)
|
||||
// Return the minimum path cost from top-left to (i, j)
|
||||
return min(left, up) + grid[i][j]
|
||||
}
|
||||
|
||||
/* Minimum path sum: Memoization search */
|
||||
func minPathSumDFSMem(grid: [[Int]], mem: inout [[Int]], i: Int, 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 .max
|
||||
}
|
||||
// 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
|
||||
let up = minPathSumDFSMem(grid: grid, mem: &mem, i: i - 1, j: j)
|
||||
let left = minPathSumDFSMem(grid: grid, mem: &mem, i: i, j: j - 1)
|
||||
// Record and return the minimum path cost from top-left to (i, j)
|
||||
mem[i][j] = min(left, up) + grid[i][j]
|
||||
return mem[i][j]
|
||||
}
|
||||
|
||||
/* Minimum path sum: Dynamic programming */
|
||||
func minPathSumDP(grid: [[Int]]) -> Int {
|
||||
let n = grid.count
|
||||
let m = grid[0].count
|
||||
// Initialize dp table
|
||||
var dp = Array(repeating: Array(repeating: 0, count: m), count: n)
|
||||
dp[0][0] = grid[0][0]
|
||||
// State transition: first row
|
||||
for j in 1 ..< m {
|
||||
dp[0][j] = dp[0][j - 1] + grid[0][j]
|
||||
}
|
||||
// State transition: first column
|
||||
for i in 1 ..< n {
|
||||
dp[i][0] = dp[i - 1][0] + grid[i][0]
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
for i in 1 ..< n {
|
||||
for j in 1 ..< m {
|
||||
dp[i][j] = min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j]
|
||||
}
|
||||
}
|
||||
return dp[n - 1][m - 1]
|
||||
}
|
||||
|
||||
/* Minimum path sum: Space-optimized dynamic programming */
|
||||
func minPathSumDPComp(grid: [[Int]]) -> Int {
|
||||
let n = grid.count
|
||||
let m = grid[0].count
|
||||
// Initialize dp table
|
||||
var dp = Array(repeating: 0, count: m)
|
||||
// State transition: first row
|
||||
dp[0] = grid[0][0]
|
||||
for j in 1 ..< m {
|
||||
dp[j] = dp[j - 1] + grid[0][j]
|
||||
}
|
||||
// State transition: rest of the rows
|
||||
for i in 1 ..< n {
|
||||
// State transition: first column
|
||||
dp[0] = dp[0] + grid[i][0]
|
||||
// State transition: rest of the columns
|
||||
for j in 1 ..< m {
|
||||
dp[j] = min(dp[j - 1], dp[j]) + grid[i][j]
|
||||
}
|
||||
}
|
||||
return dp[m - 1]
|
||||
}
|
||||
|
||||
@main
|
||||
enum MinPathSum {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let grid = [
|
||||
[1, 3, 1, 5],
|
||||
[2, 2, 4, 2],
|
||||
[5, 3, 2, 1],
|
||||
[4, 3, 5, 2],
|
||||
]
|
||||
let n = grid.count
|
||||
let m = grid[0].count
|
||||
|
||||
// Brute-force search
|
||||
var res = minPathSumDFS(grid: grid, i: n - 1, j: m - 1)
|
||||
print("Minimum path sum from top-left to bottom-right is \(res)")
|
||||
|
||||
// Memoization search
|
||||
var mem = Array(repeating: Array(repeating: -1, count: m), count: n)
|
||||
res = minPathSumDFSMem(grid: grid, mem: &mem, i: n - 1, j: m - 1)
|
||||
print("Minimum path sum from top-left to bottom-right is \(res)")
|
||||
|
||||
// Dynamic programming
|
||||
res = minPathSumDP(grid: grid)
|
||||
print("Minimum path sum from top-left to bottom-right is \(res)")
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = minPathSumDPComp(grid: grid)
|
||||
print("Minimum path sum from top-left to bottom-right is \(res)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* File: unbounded_knapsack.swift
|
||||
* Created Time: 2023-07-15
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Unbounded knapsack: Dynamic programming */
|
||||
func unboundedKnapsackDP(wgt: [Int], val: [Int], cap: Int) -> Int {
|
||||
let n = wgt.count
|
||||
// Initialize dp table
|
||||
var dp = Array(repeating: Array(repeating: 0, count: cap + 1), count: n + 1)
|
||||
// State transition
|
||||
for i in 1 ... n {
|
||||
for c in 1 ... cap {
|
||||
if wgt[i - 1] > c {
|
||||
// If exceeds knapsack capacity, don't select item i
|
||||
dp[i][c] = dp[i - 1][c]
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
dp[i][c] = max(dp[i - 1][c], dp[i][c - wgt[i - 1]] + val[i - 1])
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][cap]
|
||||
}
|
||||
|
||||
/* Unbounded knapsack: Space-optimized dynamic programming */
|
||||
func unboundedKnapsackDPComp(wgt: [Int], val: [Int], cap: Int) -> Int {
|
||||
let n = wgt.count
|
||||
// Initialize dp table
|
||||
var dp = Array(repeating: 0, count: cap + 1)
|
||||
// State transition
|
||||
for i in 1 ... n {
|
||||
for c in 1 ... cap {
|
||||
if wgt[i - 1] > c {
|
||||
// If exceeds knapsack capacity, don't select item i
|
||||
dp[c] = dp[c]
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
dp[c] = max(dp[c], dp[c - wgt[i - 1]] + val[i - 1])
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap]
|
||||
}
|
||||
|
||||
@main
|
||||
enum UnboundedKnapsack {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let wgt = [1, 2, 3]
|
||||
let val = [5, 11, 15]
|
||||
let cap = 4
|
||||
|
||||
// Dynamic programming
|
||||
var res = unboundedKnapsackDP(wgt: wgt, val: val, cap: cap)
|
||||
print("Maximum item value not exceeding knapsack capacity is \(res)")
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = unboundedKnapsackDPComp(wgt: wgt, val: val, cap: cap)
|
||||
print("Maximum item value not exceeding knapsack capacity is \(res)")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user