mirror of
https://github.com/krahets/hello-algo.git
synced 2026-04-06 04:00:21 +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:
@@ -7,24 +7,24 @@ Author: krahets (krahets@163.com)
|
||||
|
||||
def backtrack(choices: list[int], state: int, n: int, res: list[int]) -> int:
|
||||
"""Backtracking"""
|
||||
# When climbing to the nth step, add 1 to the number of solutions
|
||||
# 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: do not allow climbing beyond the nth step
|
||||
# Pruning: not allowed to go beyond the n-th stair
|
||||
if state + choice > n:
|
||||
continue
|
||||
# Attempt: make a choice, update the state
|
||||
# Attempt: make a choice, update state
|
||||
backtrack(choices, state + choice, n, res)
|
||||
# Retract
|
||||
# Backtrack
|
||||
|
||||
|
||||
def climbing_stairs_backtrack(n: int) -> int:
|
||||
"""Climbing stairs: Backtracking"""
|
||||
choices = [1, 2] # Can choose to climb up 1 step or 2 steps
|
||||
state = 0 # Start climbing from the 0th step
|
||||
res = [0] # Use res[0] to record the number of solutions
|
||||
choices = [1, 2] # Can choose to climb up 1 or 2 stairs
|
||||
state = 0 # Start climbing from the 0-th stair
|
||||
res = [0] # Use res[0] to record the solution count
|
||||
backtrack(choices, state, n, res)
|
||||
return res[0]
|
||||
|
||||
@@ -34,4 +34,4 @@ if __name__ == "__main__":
|
||||
n = 9
|
||||
|
||||
res = climbing_stairs_backtrack(n)
|
||||
print(f"Climb {n} steps, there are {res} solutions in total")
|
||||
print(f"Climbing {n} stairs has {res} solutions")
|
||||
|
||||
@@ -6,12 +6,12 @@ Author: krahets (krahets@163.com)
|
||||
|
||||
|
||||
def climbing_stairs_constraint_dp(n: int) -> int:
|
||||
"""Constrained climbing stairs: Dynamic programming"""
|
||||
"""Climbing stairs with constraint: Dynamic programming"""
|
||||
if n == 1 or n == 2:
|
||||
return 1
|
||||
# Initialize dp table, used to store subproblem solutions
|
||||
# Initialize dp table, used to store solutions to subproblems
|
||||
dp = [[0] * 3 for _ in range(n + 1)]
|
||||
# Initial state: preset the smallest subproblem solution
|
||||
# Initial state: preset the solution to the smallest subproblem
|
||||
dp[1][1], dp[1][2] = 1, 0
|
||||
dp[2][1], dp[2][2] = 0, 1
|
||||
# State transition: gradually solve larger subproblems from smaller ones
|
||||
@@ -26,4 +26,4 @@ if __name__ == "__main__":
|
||||
n = 9
|
||||
|
||||
res = climbing_stairs_constraint_dp(n)
|
||||
print(f"Climb {n} steps, there are {res} solutions in total")
|
||||
print(f"Climbing {n} stairs has {res} solutions")
|
||||
|
||||
@@ -25,4 +25,4 @@ if __name__ == "__main__":
|
||||
n = 9
|
||||
|
||||
res = climbing_stairs_dfs(n)
|
||||
print(f"Climb {n} steps, there are {res} solutions in total")
|
||||
print(f"Climbing {n} stairs has {res} solutions")
|
||||
|
||||
@@ -6,11 +6,11 @@ Author: krahets (krahets@163.com)
|
||||
|
||||
|
||||
def dfs(i: int, mem: list[int]) -> int:
|
||||
"""Memoized search"""
|
||||
"""Memoization search"""
|
||||
# Known dp[1] and dp[2], return them
|
||||
if i == 1 or i == 2:
|
||||
return i
|
||||
# If there is a record for dp[i], return it
|
||||
# If record dp[i] exists, return it directly
|
||||
if mem[i] != -1:
|
||||
return mem[i]
|
||||
# dp[i] = dp[i-1] + dp[i-2]
|
||||
@@ -21,8 +21,8 @@ def dfs(i: int, mem: list[int]) -> int:
|
||||
|
||||
|
||||
def climbing_stairs_dfs_mem(n: int) -> int:
|
||||
"""Climbing stairs: Memoized search"""
|
||||
# mem[i] records the total number of solutions for climbing to the ith step, -1 means no record
|
||||
"""Climbing stairs: Memoization search"""
|
||||
# mem[i] records the total number of solutions to climb to the i-th stair, -1 means no record
|
||||
mem = [-1] * (n + 1)
|
||||
return dfs(n, mem)
|
||||
|
||||
@@ -32,4 +32,4 @@ if __name__ == "__main__":
|
||||
n = 9
|
||||
|
||||
res = climbing_stairs_dfs_mem(n)
|
||||
print(f"Climb {n} steps, there are {res} solutions in total")
|
||||
print(f"Climbing {n} stairs has {res} solutions")
|
||||
|
||||
@@ -9,9 +9,9 @@ def climbing_stairs_dp(n: int) -> int:
|
||||
"""Climbing stairs: Dynamic programming"""
|
||||
if n == 1 or n == 2:
|
||||
return n
|
||||
# Initialize dp table, used to store subproblem solutions
|
||||
# Initialize dp table, used to store solutions to subproblems
|
||||
dp = [0] * (n + 1)
|
||||
# Initial state: preset the smallest subproblem solution
|
||||
# Initial state: preset the solution to the smallest subproblem
|
||||
dp[1], dp[2] = 1, 2
|
||||
# State transition: gradually solve larger subproblems from smaller ones
|
||||
for i in range(3, n + 1):
|
||||
@@ -34,7 +34,7 @@ if __name__ == "__main__":
|
||||
n = 9
|
||||
|
||||
res = climbing_stairs_dp(n)
|
||||
print(f"Climb {n} steps, there are {res} solutions in total")
|
||||
print(f"Climbing {n} stairs has {res} solutions")
|
||||
|
||||
res = climbing_stairs_dp_comp(n)
|
||||
print(f"Climb {n} steps, there are {res} solutions in total")
|
||||
print(f"Climbing {n} stairs has {res} solutions")
|
||||
|
||||
@@ -14,14 +14,14 @@ def coin_change_dp(coins: list[int], amt: int) -> int:
|
||||
# State transition: first row and first column
|
||||
for a in range(1, amt + 1):
|
||||
dp[0][a] = MAX
|
||||
# State transition: the rest of the rows and columns
|
||||
# State transition: rest of the rows and columns
|
||||
for i in range(1, n + 1):
|
||||
for a in range(1, amt + 1):
|
||||
if coins[i - 1] > a:
|
||||
# If exceeding the target amount, do not choose coin i
|
||||
# If exceeds target amount, don't select coin i
|
||||
dp[i][a] = dp[i - 1][a]
|
||||
else:
|
||||
# The smaller value between not choosing and choosing coin i
|
||||
# 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] if dp[n][amt] != MAX else -1
|
||||
|
||||
@@ -35,13 +35,13 @@ def coin_change_dp_comp(coins: list[int], amt: int) -> int:
|
||||
dp[0] = 0
|
||||
# State transition
|
||||
for i in range(1, n + 1):
|
||||
# Traverse in order
|
||||
# Traverse in forward order
|
||||
for a in range(1, amt + 1):
|
||||
if coins[i - 1] > a:
|
||||
# If exceeding the target amount, do not choose coin i
|
||||
# If exceeds target amount, don't select coin i
|
||||
dp[a] = dp[a]
|
||||
else:
|
||||
# The smaller value between not choosing and choosing coin i
|
||||
# The smaller value between not selecting and selecting coin i
|
||||
dp[a] = min(dp[a], dp[a - coins[i - 1]] + 1)
|
||||
return dp[amt] if dp[amt] != MAX else -1
|
||||
|
||||
@@ -53,8 +53,8 @@ if __name__ == "__main__":
|
||||
|
||||
# Dynamic programming
|
||||
res = coin_change_dp(coins, amt)
|
||||
print(f"Minimum number of coins required to reach the target amount = {res}")
|
||||
print(f"The minimum number of coins needed to make up the target amount is {res}")
|
||||
|
||||
# Space-optimized dynamic programming
|
||||
res = coin_change_dp_comp(coins, amt)
|
||||
print(f"Minimum number of coins required to reach the target amount = {res}")
|
||||
print(f"The minimum number of coins needed to make up the target amount is {res}")
|
||||
|
||||
@@ -17,10 +17,10 @@ def coin_change_ii_dp(coins: list[int], amt: int) -> int:
|
||||
for i in range(1, n + 1):
|
||||
for a in range(1, amt + 1):
|
||||
if coins[i - 1] > a:
|
||||
# If exceeding the target amount, do not choose coin i
|
||||
# If exceeds target amount, don't select coin i
|
||||
dp[i][a] = dp[i - 1][a]
|
||||
else:
|
||||
# The sum of the two options of not choosing and choosing coin i
|
||||
# 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]
|
||||
|
||||
@@ -33,13 +33,13 @@ def coin_change_ii_dp_comp(coins: list[int], amt: int) -> int:
|
||||
dp[0] = 1
|
||||
# State transition
|
||||
for i in range(1, n + 1):
|
||||
# Traverse in order
|
||||
# Traverse in forward order
|
||||
for a in range(1, amt + 1):
|
||||
if coins[i - 1] > a:
|
||||
# If exceeding the target amount, do not choose coin i
|
||||
# If exceeds target amount, don't select coin i
|
||||
dp[a] = dp[a]
|
||||
else:
|
||||
# The sum of the two options of not choosing and choosing coin i
|
||||
# Sum of the two options: not selecting and selecting coin i
|
||||
dp[a] = dp[a] + dp[a - coins[i - 1]]
|
||||
return dp[amt]
|
||||
|
||||
|
||||
@@ -6,49 +6,49 @@ Author: krahets (krahets@163.com)
|
||||
|
||||
|
||||
def edit_distance_dfs(s: str, t: str, i: int, j: int) -> int:
|
||||
"""Edit distance: Brute force search"""
|
||||
"""Edit distance: Brute-force search"""
|
||||
# If both s and t are empty, return 0
|
||||
if i == 0 and j == 0:
|
||||
return 0
|
||||
# If s is empty, return the length of t
|
||||
# If s is empty, return length of t
|
||||
if i == 0:
|
||||
return j
|
||||
# If t is empty, return the length of s
|
||||
# If t is empty, return length of s
|
||||
if j == 0:
|
||||
return i
|
||||
# If the two characters are equal, skip these two characters
|
||||
# If two characters are equal, skip both characters
|
||||
if s[i - 1] == t[j - 1]:
|
||||
return edit_distance_dfs(s, t, i - 1, j - 1)
|
||||
# The minimum number of edits = the minimum number of edits from three operations (insert, remove, replace) + 1
|
||||
# Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
insert = edit_distance_dfs(s, t, i, j - 1)
|
||||
delete = edit_distance_dfs(s, t, i - 1, j)
|
||||
replace = edit_distance_dfs(s, t, i - 1, j - 1)
|
||||
# Return the minimum number of edits
|
||||
# Return minimum edit steps
|
||||
return min(insert, delete, replace) + 1
|
||||
|
||||
|
||||
def edit_distance_dfs_mem(s: str, t: str, mem: list[list[int]], i: int, j: int) -> int:
|
||||
"""Edit distance: Memoized search"""
|
||||
"""Edit distance: Memoization search"""
|
||||
# If both s and t are empty, return 0
|
||||
if i == 0 and j == 0:
|
||||
return 0
|
||||
# If s is empty, return the length of t
|
||||
# If s is empty, return length of t
|
||||
if i == 0:
|
||||
return j
|
||||
# If t is empty, return the length of s
|
||||
# If t is empty, return length of s
|
||||
if j == 0:
|
||||
return i
|
||||
# If there is a record, return it
|
||||
# If there's a record, return it directly
|
||||
if mem[i][j] != -1:
|
||||
return mem[i][j]
|
||||
# If the two characters are equal, skip these two characters
|
||||
# If two characters are equal, skip both characters
|
||||
if s[i - 1] == t[j - 1]:
|
||||
return edit_distance_dfs_mem(s, t, mem, i - 1, j - 1)
|
||||
# The minimum number of edits = the minimum number of edits from three operations (insert, remove, replace) + 1
|
||||
# Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
insert = edit_distance_dfs_mem(s, t, mem, i, j - 1)
|
||||
delete = edit_distance_dfs_mem(s, t, mem, i - 1, j)
|
||||
replace = edit_distance_dfs_mem(s, t, mem, i - 1, j - 1)
|
||||
# Record and return the minimum number of edits
|
||||
# Record and return minimum edit steps
|
||||
mem[i][j] = min(insert, delete, replace) + 1
|
||||
return mem[i][j]
|
||||
|
||||
@@ -62,14 +62,14 @@ def edit_distance_dp(s: str, t: str) -> int:
|
||||
dp[i][0] = i
|
||||
for j in range(1, m + 1):
|
||||
dp[0][j] = j
|
||||
# State transition: the rest of the rows and columns
|
||||
# State transition: rest of the rows and columns
|
||||
for i in range(1, n + 1):
|
||||
for j in range(1, m + 1):
|
||||
if s[i - 1] == t[j - 1]:
|
||||
# If the two characters are equal, skip these two characters
|
||||
# If two characters are equal, skip both characters
|
||||
dp[i][j] = dp[i - 1][j - 1]
|
||||
else:
|
||||
# The minimum number of edits = the minimum number of edits from three operations (insert, remove, replace) + 1
|
||||
# Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
dp[i][j] = min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]) + 1
|
||||
return dp[n][m]
|
||||
|
||||
@@ -81,21 +81,21 @@ def edit_distance_dp_comp(s: str, t: str) -> int:
|
||||
# State transition: first row
|
||||
for j in range(1, m + 1):
|
||||
dp[j] = j
|
||||
# State transition: the rest of the rows
|
||||
# State transition: rest of the rows
|
||||
for i in range(1, n + 1):
|
||||
# State transition: first column
|
||||
leftup = dp[0] # Temporarily store dp[i-1, j-1]
|
||||
dp[0] += 1
|
||||
# State transition: the rest of the columns
|
||||
# State transition: rest of the columns
|
||||
for j in range(1, m + 1):
|
||||
temp = dp[j]
|
||||
if s[i - 1] == t[j - 1]:
|
||||
# If the two characters are equal, skip these two characters
|
||||
# If two characters are equal, skip both characters
|
||||
dp[j] = leftup
|
||||
else:
|
||||
# The minimum number of edits = the minimum number of edits from three operations (insert, remove, replace) + 1
|
||||
# Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
dp[j] = min(dp[j - 1], dp[j], leftup) + 1
|
||||
leftup = temp # Update for the next round of dp[i-1, j-1]
|
||||
leftup = temp # Update for next round's dp[i-1, j-1]
|
||||
return dp[m]
|
||||
|
||||
|
||||
@@ -105,19 +105,19 @@ if __name__ == "__main__":
|
||||
t = "pack"
|
||||
n, m = len(s), len(t)
|
||||
|
||||
# Brute force search
|
||||
# Brute-force search
|
||||
res = edit_distance_dfs(s, t, n, m)
|
||||
print(f"To change {s} to {t}, the minimum number of edits required is {res}")
|
||||
print(f"Changing {s} to {t} requires a minimum of {res} edits")
|
||||
|
||||
# Memoized search
|
||||
# Memoization search
|
||||
mem = [[-1] * (m + 1) for _ in range(n + 1)]
|
||||
res = edit_distance_dfs_mem(s, t, mem, n, m)
|
||||
print(f"To change {s} to {t}, the minimum number of edits required is {res}")
|
||||
print(f"Changing {s} to {t} requires a minimum of {res} edits")
|
||||
|
||||
# Dynamic programming
|
||||
res = edit_distance_dp(s, t)
|
||||
print(f"To change {s} to {t}, the minimum number of edits required is {res}")
|
||||
print(f"Changing {s} to {t} requires a minimum of {res} edits")
|
||||
|
||||
# Space-optimized dynamic programming
|
||||
res = edit_distance_dp_comp(s, t)
|
||||
print(f"To change {s} to {t}, the minimum number of edits required is {res}")
|
||||
print(f"Changing {s} to {t} requires a minimum of {res} edits")
|
||||
|
||||
@@ -6,43 +6,43 @@ Author: krahets (krahets@163.com)
|
||||
|
||||
|
||||
def knapsack_dfs(wgt: list[int], val: list[int], i: int, c: int) -> int:
|
||||
"""0-1 Knapsack: Brute force search"""
|
||||
# If all items have been chosen or the knapsack has no remaining capacity, return value 0
|
||||
"""0-1 knapsack: Brute-force search"""
|
||||
# If all items have been selected or knapsack has no remaining capacity, return value 0
|
||||
if i == 0 or c == 0:
|
||||
return 0
|
||||
# If exceeding the knapsack capacity, can only choose not to put it in the knapsack
|
||||
# If exceeds knapsack capacity, can only choose not to put it in
|
||||
if wgt[i - 1] > c:
|
||||
return knapsack_dfs(wgt, val, i - 1, c)
|
||||
# Calculate the maximum value of not putting in and putting in item i
|
||||
no = knapsack_dfs(wgt, val, i - 1, c)
|
||||
yes = knapsack_dfs(wgt, val, i - 1, c - wgt[i - 1]) + val[i - 1]
|
||||
# Return the greater value of the two options
|
||||
# Return the larger value of the two options
|
||||
return max(no, yes)
|
||||
|
||||
|
||||
def knapsack_dfs_mem(
|
||||
wgt: list[int], val: list[int], mem: list[list[int]], i: int, c: int
|
||||
) -> int:
|
||||
"""0-1 Knapsack: Memoized search"""
|
||||
# If all items have been chosen or the knapsack has no remaining capacity, return value 0
|
||||
"""0-1 knapsack: Memoization search"""
|
||||
# If all items have been selected or knapsack has no remaining capacity, return value 0
|
||||
if i == 0 or c == 0:
|
||||
return 0
|
||||
# If there is a record, return it
|
||||
# If there's a record, return it directly
|
||||
if mem[i][c] != -1:
|
||||
return mem[i][c]
|
||||
# If exceeding the knapsack capacity, can only choose not to put it in the knapsack
|
||||
# If exceeds knapsack capacity, can only choose not to put it in
|
||||
if wgt[i - 1] > c:
|
||||
return knapsack_dfs_mem(wgt, val, mem, i - 1, c)
|
||||
# Calculate the maximum value of not putting in and putting in item i
|
||||
no = knapsack_dfs_mem(wgt, val, mem, i - 1, c)
|
||||
yes = knapsack_dfs_mem(wgt, val, mem, i - 1, c - wgt[i - 1]) + val[i - 1]
|
||||
# Record and return the greater value of the two options
|
||||
# Record and return the larger value of the two options
|
||||
mem[i][c] = max(no, yes)
|
||||
return mem[i][c]
|
||||
|
||||
|
||||
def knapsack_dp(wgt: list[int], val: list[int], cap: int) -> int:
|
||||
"""0-1 Knapsack: Dynamic programming"""
|
||||
"""0-1 knapsack: Dynamic programming"""
|
||||
n = len(wgt)
|
||||
# Initialize dp table
|
||||
dp = [[0] * (cap + 1) for _ in range(n + 1)]
|
||||
@@ -50,16 +50,16 @@ def knapsack_dp(wgt: list[int], val: list[int], cap: int) -> int:
|
||||
for i in range(1, n + 1):
|
||||
for c in range(1, cap + 1):
|
||||
if wgt[i - 1] > c:
|
||||
# If exceeding the knapsack capacity, do not choose item i
|
||||
# If exceeds knapsack capacity, don't select item i
|
||||
dp[i][c] = dp[i - 1][c]
|
||||
else:
|
||||
# The greater value between not choosing and choosing item i
|
||||
# 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]
|
||||
|
||||
|
||||
def knapsack_dp_comp(wgt: list[int], val: list[int], cap: int) -> int:
|
||||
"""0-1 Knapsack: Space-optimized dynamic programming"""
|
||||
"""0-1 knapsack: Space-optimized dynamic programming"""
|
||||
n = len(wgt)
|
||||
# Initialize dp table
|
||||
dp = [0] * (cap + 1)
|
||||
@@ -68,10 +68,10 @@ def knapsack_dp_comp(wgt: list[int], val: list[int], cap: int) -> int:
|
||||
# Traverse in reverse order
|
||||
for c in range(cap, 0, -1):
|
||||
if wgt[i - 1] > c:
|
||||
# If exceeding the knapsack capacity, do not choose item i
|
||||
# If exceeds knapsack capacity, don't select item i
|
||||
dp[c] = dp[c]
|
||||
else:
|
||||
# The greater value between not choosing and choosing item i
|
||||
# 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]
|
||||
|
||||
@@ -83,19 +83,19 @@ if __name__ == "__main__":
|
||||
cap = 50
|
||||
n = len(wgt)
|
||||
|
||||
# Brute force search
|
||||
# Brute-force search
|
||||
res = knapsack_dfs(wgt, val, n, cap)
|
||||
print(f"The maximum item value without exceeding knapsack capacity is {res}")
|
||||
print(f"The maximum item value not exceeding knapsack capacity is {res}")
|
||||
|
||||
# Memoized search
|
||||
# Memoization search
|
||||
mem = [[-1] * (cap + 1) for _ in range(n + 1)]
|
||||
res = knapsack_dfs_mem(wgt, val, mem, n, cap)
|
||||
print(f"The maximum item value without exceeding knapsack capacity is {res}")
|
||||
print(f"The maximum item value not exceeding knapsack capacity is {res}")
|
||||
|
||||
# Dynamic programming
|
||||
res = knapsack_dp(wgt, val, cap)
|
||||
print(f"The maximum item value without exceeding knapsack capacity is {res}")
|
||||
print(f"The maximum item value not exceeding knapsack capacity is {res}")
|
||||
|
||||
# Space-optimized dynamic programming
|
||||
res = knapsack_dp_comp(wgt, val, cap)
|
||||
print(f"The maximum item value without exceeding knapsack capacity is {res}")
|
||||
print(f"The maximum item value not exceeding knapsack capacity is {res}")
|
||||
|
||||
@@ -6,13 +6,13 @@ Author: krahets (krahets@163.com)
|
||||
|
||||
|
||||
def min_cost_climbing_stairs_dp(cost: list[int]) -> int:
|
||||
"""Climbing stairs with minimum cost: Dynamic programming"""
|
||||
"""Minimum cost climbing stairs: Dynamic programming"""
|
||||
n = len(cost) - 1
|
||||
if n == 1 or n == 2:
|
||||
return cost[n]
|
||||
# Initialize dp table, used to store subproblem solutions
|
||||
# Initialize dp table, used to store solutions to subproblems
|
||||
dp = [0] * (n + 1)
|
||||
# Initial state: preset the smallest subproblem solution
|
||||
# Initial state: preset the solution to the smallest subproblem
|
||||
dp[1], dp[2] = cost[1], cost[2]
|
||||
# State transition: gradually solve larger subproblems from smaller ones
|
||||
for i in range(3, n + 1):
|
||||
@@ -21,7 +21,7 @@ def min_cost_climbing_stairs_dp(cost: list[int]) -> int:
|
||||
|
||||
|
||||
def min_cost_climbing_stairs_dp_comp(cost: list[int]) -> int:
|
||||
"""Climbing stairs with minimum cost: Space-optimized dynamic programming"""
|
||||
"""Minimum cost climbing stairs: Space-optimized dynamic programming"""
|
||||
n = len(cost) - 1
|
||||
if n == 1 or n == 2:
|
||||
return cost[n]
|
||||
@@ -34,10 +34,10 @@ def min_cost_climbing_stairs_dp_comp(cost: list[int]) -> int:
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
cost = [0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1]
|
||||
print(f"Enter the list of stair costs as {cost}")
|
||||
print(f"Input stair cost list is {cost}")
|
||||
|
||||
res = min_cost_climbing_stairs_dp(cost)
|
||||
print(f"Minimum cost to climb the stairs {res}")
|
||||
print(f"The minimum cost to finish climbing the stairs is {res}")
|
||||
|
||||
res = min_cost_climbing_stairs_dp_comp(cost)
|
||||
print(f"Minimum cost to climb the stairs {res}")
|
||||
print(f"The minimum cost to finish climbing the stairs is {res}")
|
||||
|
||||
@@ -8,37 +8,37 @@ from math import inf
|
||||
|
||||
|
||||
def min_path_sum_dfs(grid: list[list[int]], i: int, j: int) -> int:
|
||||
"""Minimum path sum: Brute force search"""
|
||||
"""Minimum path sum: Brute-force search"""
|
||||
# If it's the top-left cell, terminate the search
|
||||
if i == 0 and j == 0:
|
||||
return grid[0][0]
|
||||
# If the row or column index is out of bounds, return a +∞ cost
|
||||
# If row or column index is out of bounds, return +∞ cost
|
||||
if i < 0 or j < 0:
|
||||
return inf
|
||||
# Calculate the minimum path cost from the top-left to (i-1, j) and (i, j-1)
|
||||
# Calculate the minimum path cost from top-left to (i-1, j) and (i, j-1)
|
||||
up = min_path_sum_dfs(grid, i - 1, j)
|
||||
left = min_path_sum_dfs(grid, i, j - 1)
|
||||
# Return the minimum path cost from the top-left to (i, j)
|
||||
# Return the minimum path cost from top-left to (i, j)
|
||||
return min(left, up) + grid[i][j]
|
||||
|
||||
|
||||
def min_path_sum_dfs_mem(
|
||||
grid: list[list[int]], mem: list[list[int]], i: int, j: int
|
||||
) -> int:
|
||||
"""Minimum path sum: Memoized search"""
|
||||
"""Minimum path sum: Memoization search"""
|
||||
# If it's the top-left cell, terminate the search
|
||||
if i == 0 and j == 0:
|
||||
return grid[0][0]
|
||||
# If the row or column index is out of bounds, return a +∞ cost
|
||||
# If row or column index is out of bounds, return +∞ cost
|
||||
if i < 0 or j < 0:
|
||||
return inf
|
||||
# If there is a record, return it
|
||||
# If there's a record, return it directly
|
||||
if mem[i][j] != -1:
|
||||
return mem[i][j]
|
||||
# The minimum path cost from the left and top cells
|
||||
# Minimum path cost for left and upper cells
|
||||
up = min_path_sum_dfs_mem(grid, mem, i - 1, j)
|
||||
left = min_path_sum_dfs_mem(grid, mem, i, j - 1)
|
||||
# Record and return the minimum path cost from the top-left to (i, j)
|
||||
# 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]
|
||||
|
||||
@@ -55,7 +55,7 @@ def min_path_sum_dp(grid: list[list[int]]) -> int:
|
||||
# State transition: first column
|
||||
for i in range(1, n):
|
||||
dp[i][0] = dp[i - 1][0] + grid[i][0]
|
||||
# State transition: the rest of the rows and columns
|
||||
# State transition: rest of the rows and columns
|
||||
for i in range(1, n):
|
||||
for j in range(1, m):
|
||||
dp[i][j] = min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j]
|
||||
@@ -71,11 +71,11 @@ def min_path_sum_dp_comp(grid: list[list[int]]) -> int:
|
||||
dp[0] = grid[0][0]
|
||||
for j in range(1, m):
|
||||
dp[j] = dp[j - 1] + grid[0][j]
|
||||
# State transition: the rest of the rows
|
||||
# State transition: rest of the rows
|
||||
for i in range(1, n):
|
||||
# State transition: first column
|
||||
dp[0] = dp[0] + grid[i][0]
|
||||
# State transition: the rest of the columns
|
||||
# State transition: rest of the columns
|
||||
for j in range(1, m):
|
||||
dp[j] = min(dp[j - 1], dp[j]) + grid[i][j]
|
||||
return dp[m - 1]
|
||||
@@ -86,19 +86,19 @@ if __name__ == "__main__":
|
||||
grid = [[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
|
||||
# Brute-force search
|
||||
res = min_path_sum_dfs(grid, n - 1, m - 1)
|
||||
print(f"The minimum path sum from the top-left to the bottom-right corner is {res}")
|
||||
print(f"The minimum path sum from top-left to bottom-right is {res}")
|
||||
|
||||
# Memoized search
|
||||
# Memoization search
|
||||
mem = [[-1] * m for _ in range(n)]
|
||||
res = min_path_sum_dfs_mem(grid, mem, n - 1, m - 1)
|
||||
print(f"The minimum path sum from the top-left to the bottom-right corner is {res}")
|
||||
print(f"The minimum path sum from top-left to bottom-right is {res}")
|
||||
|
||||
# Dynamic programming
|
||||
res = min_path_sum_dp(grid)
|
||||
print(f"The minimum path sum from the top-left to the bottom-right corner is {res}")
|
||||
print(f"The minimum path sum from top-left to bottom-right is {res}")
|
||||
|
||||
# Space-optimized dynamic programming
|
||||
res = min_path_sum_dp_comp(grid)
|
||||
print(f"The minimum path sum from the top-left to the bottom-right corner is {res}")
|
||||
print(f"The minimum path sum from top-left to bottom-right is {res}")
|
||||
|
||||
@@ -6,7 +6,7 @@ Author: krahets (krahets@163.com)
|
||||
|
||||
|
||||
def unbounded_knapsack_dp(wgt: list[int], val: list[int], cap: int) -> int:
|
||||
"""Complete knapsack: Dynamic programming"""
|
||||
"""Unbounded knapsack: Dynamic programming"""
|
||||
n = len(wgt)
|
||||
# Initialize dp table
|
||||
dp = [[0] * (cap + 1) for _ in range(n + 1)]
|
||||
@@ -14,28 +14,28 @@ def unbounded_knapsack_dp(wgt: list[int], val: list[int], cap: int) -> int:
|
||||
for i in range(1, n + 1):
|
||||
for c in range(1, cap + 1):
|
||||
if wgt[i - 1] > c:
|
||||
# If exceeding the knapsack capacity, do not choose item i
|
||||
# If exceeds knapsack capacity, don't select item i
|
||||
dp[i][c] = dp[i - 1][c]
|
||||
else:
|
||||
# The greater value between not choosing and choosing item i
|
||||
# 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]
|
||||
|
||||
|
||||
def unbounded_knapsack_dp_comp(wgt: list[int], val: list[int], cap: int) -> int:
|
||||
"""Complete knapsack: Space-optimized dynamic programming"""
|
||||
"""Unbounded knapsack: Space-optimized dynamic programming"""
|
||||
n = len(wgt)
|
||||
# Initialize dp table
|
||||
dp = [0] * (cap + 1)
|
||||
# State transition
|
||||
for i in range(1, n + 1):
|
||||
# Traverse in order
|
||||
# Traverse in forward order
|
||||
for c in range(1, cap + 1):
|
||||
if wgt[i - 1] > c:
|
||||
# If exceeding the knapsack capacity, do not choose item i
|
||||
# If exceeds knapsack capacity, don't select item i
|
||||
dp[c] = dp[c]
|
||||
else:
|
||||
# The greater value between not choosing and choosing item i
|
||||
# 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]
|
||||
|
||||
@@ -48,8 +48,8 @@ if __name__ == "__main__":
|
||||
|
||||
# Dynamic programming
|
||||
res = unbounded_knapsack_dp(wgt, val, cap)
|
||||
print(f"The maximum item value without exceeding knapsack capacity is {res}")
|
||||
print(f"The maximum item value not exceeding knapsack capacity is {res}")
|
||||
|
||||
# Space-optimized dynamic programming
|
||||
res = unbounded_knapsack_dp_comp(wgt, val, cap)
|
||||
print(f"The maximum item value without exceeding knapsack capacity is {res}")
|
||||
print(f"The maximum item value not exceeding knapsack capacity is {res}")
|
||||
|
||||
Reference in New Issue
Block a user