translation: Add Python and Java code for EN version (#1345)

* Add the intial translation of code of all the languages

* test

* revert

* Remove

* Add Python and Java code for EN version
This commit is contained in:
Yudong Jin
2024-05-06 05:21:51 +08:00
committed by GitHub
parent b5e198db7d
commit 1c0f350ad6
174 changed files with 12349 additions and 0 deletions

View File

@ -0,0 +1,37 @@
"""
File: climbing_stairs_backtrack.py
Created Time: 2023-06-30
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
if state == n:
res[0] += 1
# Traverse all choices
for choice in choices:
# Pruning: do not allow climbing beyond the nth step
if state + choice > n:
continue
# Attempt: make a choice, update the state
backtrack(choices, state + choice, n, res)
# Retract
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
backtrack(choices, state, n, res)
return res[0]
"""Driver Code"""
if __name__ == "__main__":
n = 9
res = climbing_stairs_backtrack(n)
print(f"Climb {n} steps, there are {res} solutions in total")

View File

@ -0,0 +1,29 @@
"""
File: climbing_stairs_constraint_dp.py
Created Time: 2023-06-30
Author: krahets (krahets@163.com)
"""
def climbing_stairs_constraint_dp(n: int) -> int:
"""Constrained climbing stairs: Dynamic programming"""
if n == 1 or n == 2:
return 1
# Initialize dp table, used to store subproblem solutions
dp = [[0] * 3 for _ in range(n + 1)]
# Initial state: preset the smallest subproblem solution
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
for i in range(3, n + 1):
dp[i][1] = dp[i - 1][2]
dp[i][2] = dp[i - 2][1] + dp[i - 2][2]
return dp[n][1] + dp[n][2]
"""Driver Code"""
if __name__ == "__main__":
n = 9
res = climbing_stairs_constraint_dp(n)
print(f"Climb {n} steps, there are {res} solutions in total")

View File

@ -0,0 +1,28 @@
"""
File: climbing_stairs_dfs.py
Created Time: 2023-06-30
Author: krahets (krahets@163.com)
"""
def dfs(i: int) -> int:
"""Search"""
# Known dp[1] and dp[2], return them
if i == 1 or i == 2:
return i
# dp[i] = dp[i-1] + dp[i-2]
count = dfs(i - 1) + dfs(i - 2)
return count
def climbing_stairs_dfs(n: int) -> int:
"""Climbing stairs: Search"""
return dfs(n)
"""Driver Code"""
if __name__ == "__main__":
n = 9
res = climbing_stairs_dfs(n)
print(f"Climb {n} steps, there are {res} solutions in total")

View File

@ -0,0 +1,35 @@
"""
File: climbing_stairs_dfs_mem.py
Created Time: 2023-06-30
Author: krahets (krahets@163.com)
"""
def dfs(i: int, mem: list[int]) -> int:
"""Memoized 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 mem[i] != -1:
return mem[i]
# dp[i] = dp[i-1] + dp[i-2]
count = dfs(i - 1, mem) + dfs(i - 2, mem)
# Record dp[i]
mem[i] = count
return count
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
mem = [-1] * (n + 1)
return dfs(n, mem)
"""Driver Code"""
if __name__ == "__main__":
n = 9
res = climbing_stairs_dfs_mem(n)
print(f"Climb {n} steps, there are {res} solutions in total")

View File

@ -0,0 +1,40 @@
"""
File: climbing_stairs_dp.py
Created Time: 2023-06-30
Author: krahets (krahets@163.com)
"""
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
dp = [0] * (n + 1)
# Initial state: preset the smallest subproblem solution
dp[1], dp[2] = 1, 2
# State transition: gradually solve larger subproblems from smaller ones
for i in range(3, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
def climbing_stairs_dp_comp(n: int) -> int:
"""Climbing stairs: Space-optimized dynamic programming"""
if n == 1 or n == 2:
return n
a, b = 1, 2
for _ in range(3, n + 1):
a, b = b, a + b
return b
"""Driver Code"""
if __name__ == "__main__":
n = 9
res = climbing_stairs_dp(n)
print(f"Climb {n} steps, there are {res} solutions in total")
res = climbing_stairs_dp_comp(n)
print(f"Climb {n} steps, there are {res} solutions in total")

View File

@ -0,0 +1,60 @@
"""
File: coin_change.py
Created Time: 2023-07-10
Author: krahets (krahets@163.com)
"""
def coin_change_dp(coins: list[int], amt: int) -> int:
"""Coin change: Dynamic programming"""
n = len(coins)
MAX = amt + 1
# Initialize dp table
dp = [[0] * (amt + 1) for _ in range(n + 1)]
# 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
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
dp[i][a] = dp[i - 1][a]
else:
# The smaller value between not choosing and choosing 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
def coin_change_dp_comp(coins: list[int], amt: int) -> int:
"""Coin change: Space-optimized dynamic programming"""
n = len(coins)
MAX = amt + 1
# Initialize dp table
dp = [MAX] * (amt + 1)
dp[0] = 0
# State transition
for i in range(1, n + 1):
# Traverse in order
for a in range(1, amt + 1):
if coins[i - 1] > a:
# If exceeding the target amount, do not choose coin i
dp[a] = dp[a]
else:
# The smaller value between not choosing and choosing coin i
dp[a] = min(dp[a], dp[a - coins[i - 1]] + 1)
return dp[amt] if dp[amt] != MAX else -1
"""Driver Code"""
if __name__ == "__main__":
coins = [1, 2, 5]
amt = 4
# Dynamic programming
res = coin_change_dp(coins, amt)
print(f"Minimum number of coins required to reach the target amount = {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}")

View File

@ -0,0 +1,58 @@
"""
File: coin_change_ii.py
Created Time: 2023-07-10
Author: krahets (krahets@163.com)
"""
def coin_change_ii_dp(coins: list[int], amt: int) -> int:
"""Coin change II: Dynamic programming"""
n = len(coins)
# Initialize dp table
dp = [[0] * (amt + 1) for _ in range(n + 1)]
# Initialize first column
for i in range(n + 1):
dp[i][0] = 1
# State transition
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
dp[i][a] = dp[i - 1][a]
else:
# The sum of the two options of not choosing and choosing coin i
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]]
return dp[n][amt]
def coin_change_ii_dp_comp(coins: list[int], amt: int) -> int:
"""Coin change II: Space-optimized dynamic programming"""
n = len(coins)
# Initialize dp table
dp = [0] * (amt + 1)
dp[0] = 1
# State transition
for i in range(1, n + 1):
# Traverse in order
for a in range(1, amt + 1):
if coins[i - 1] > a:
# If exceeding the target amount, do not choose coin i
dp[a] = dp[a]
else:
# The sum of the two options of not choosing and choosing coin i
dp[a] = dp[a] + dp[a - coins[i - 1]]
return dp[amt]
"""Driver Code"""
if __name__ == "__main__":
coins = [1, 2, 5]
amt = 5
# Dynamic programming
res = coin_change_ii_dp(coins, amt)
print(f"The number of coin combinations to make up the target amount is {res}")
# Space-optimized dynamic programming
res = coin_change_ii_dp_comp(coins, amt)
print(f"The number of coin combinations to make up the target amount is {res}")

View File

@ -0,0 +1,123 @@
"""
File: edit_distancde.py
Created Time: 2023-07-04
Author: krahets (krahets@163.com)
"""
def edit_distance_dfs(s: str, t: str, i: int, j: int) -> int:
"""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 i == 0:
return j
# If t is empty, return the length of s
if j == 0:
return i
# If the two characters are equal, skip these two 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
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 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"""
# 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 i == 0:
return j
# If t is empty, return the length of s
if j == 0:
return i
# If there is a record, return it
if mem[i][j] != -1:
return mem[i][j]
# If the two characters are equal, skip these two 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
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
mem[i][j] = min(insert, delete, replace) + 1
return mem[i][j]
def edit_distance_dp(s: str, t: str) -> int:
"""Edit distance: Dynamic programming"""
n, m = len(s), len(t)
dp = [[0] * (m + 1) for _ in range(n + 1)]
# State transition: first row and first column
for i in range(1, n + 1):
dp[i][0] = i
for j in range(1, m + 1):
dp[0][j] = j
# State transition: the 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
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
dp[i][j] = min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]) + 1
return dp[n][m]
def edit_distance_dp_comp(s: str, t: str) -> int:
"""Edit distance: Space-optimized dynamic programming"""
n, m = len(s), len(t)
dp = [0] * (m + 1)
# State transition: first row
for j in range(1, m + 1):
dp[j] = j
# State transition: the 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
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
dp[j] = leftup
else:
# The minimum number of edits = the minimum number of edits from three operations (insert, remove, 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]
return dp[m]
"""Driver Code"""
if __name__ == "__main__":
s = "bag"
t = "pack"
n, m = len(s), len(t)
# 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}")
# Memoized 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}")
# Dynamic programming
res = edit_distance_dp(s, t)
print(f"To change {s} to {t}, the minimum number of edits required is {res}")
# 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}")

View File

@ -0,0 +1,101 @@
"""
File: knapsack.py
Created Time: 2023-07-03
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
if i == 0 or c == 0:
return 0
# If exceeding the knapsack capacity, can only choose not to put it in the knapsack
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 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
if i == 0 or c == 0:
return 0
# If there is a record, return it
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 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
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"""
n = len(wgt)
# Initialize dp table
dp = [[0] * (cap + 1) for _ in range(n + 1)]
# State transition
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
dp[i][c] = dp[i - 1][c]
else:
# The greater value between not choosing and choosing 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"""
n = len(wgt)
# Initialize dp table
dp = [0] * (cap + 1)
# State transition
for i in range(1, n + 1):
# 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
dp[c] = dp[c]
else:
# The greater value between not choosing and choosing item i
dp[c] = max(dp[c], dp[c - wgt[i - 1]] + val[i - 1])
return dp[cap]
"""Driver Code"""
if __name__ == "__main__":
wgt = [10, 20, 30, 40, 50]
val = [50, 120, 150, 210, 240]
cap = 50
n = len(wgt)
# Brute force search
res = knapsack_dfs(wgt, val, n, cap)
print(f"The maximum item value without exceeding knapsack capacity is {res}")
# Memoized 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}")
# Dynamic programming
res = knapsack_dp(wgt, val, cap)
print(f"The maximum item value without 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}")

View File

@ -0,0 +1,43 @@
"""
File: min_cost_climbing_stairs_dp.py
Created Time: 2023-06-30
Author: krahets (krahets@163.com)
"""
def min_cost_climbing_stairs_dp(cost: list[int]) -> int:
"""Climbing stairs with minimum cost: Dynamic programming"""
n = len(cost) - 1
if n == 1 or n == 2:
return cost[n]
# Initialize dp table, used to store subproblem solutions
dp = [0] * (n + 1)
# Initial state: preset the smallest subproblem solution
dp[1], dp[2] = cost[1], cost[2]
# State transition: gradually solve larger subproblems from smaller ones
for i in range(3, n + 1):
dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i]
return dp[n]
def min_cost_climbing_stairs_dp_comp(cost: list[int]) -> int:
"""Climbing stairs with minimum cost: Space-optimized dynamic programming"""
n = len(cost) - 1
if n == 1 or n == 2:
return cost[n]
a, b = cost[1], cost[2]
for i in range(3, n + 1):
a, b = b, min(a, b) + cost[i]
return b
"""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}")
res = min_cost_climbing_stairs_dp(cost)
print(f"Minimum cost to climb the stairs {res}")
res = min_cost_climbing_stairs_dp_comp(cost)
print(f"Minimum cost to climb the stairs {res}")

View File

@ -0,0 +1,104 @@
"""
File: min_path_sum.py
Created Time: 2023-07-04
Author: krahets (krahets@163.com)
"""
from math import inf
def min_path_sum_dfs(grid: list[list[int]], i: int, j: int) -> int:
"""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 i < 0 or j < 0:
return inf
# Calculate the minimum path cost from the 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 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"""
# 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 i < 0 or j < 0:
return inf
# If there is a record, return it
if mem[i][j] != -1:
return mem[i][j]
# The minimum path cost from the left and top 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)
mem[i][j] = min(left, up) + grid[i][j]
return mem[i][j]
def min_path_sum_dp(grid: list[list[int]]) -> int:
"""Minimum path sum: Dynamic programming"""
n, m = len(grid), len(grid[0])
# Initialize dp table
dp = [[0] * m for _ in range(n)]
dp[0][0] = grid[0][0]
# State transition: first row
for j in range(1, m):
dp[0][j] = dp[0][j - 1] + grid[0][j]
# 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
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]
return dp[n - 1][m - 1]
def min_path_sum_dp_comp(grid: list[list[int]]) -> int:
"""Minimum path sum: Space-optimized dynamic programming"""
n, m = len(grid), len(grid[0])
# Initialize dp table
dp = [0] * m
# State transition: first row
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
for i in range(1, n):
# State transition: first column
dp[0] = dp[0] + grid[i][0]
# State transition: the 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]
"""Driver Code"""
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
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}")
# Memoized 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}")
# 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}")
# 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}")

View File

@ -0,0 +1,55 @@
"""
File: unbounded_knapsack.py
Created Time: 2023-07-10
Author: krahets (krahets@163.com)
"""
def unbounded_knapsack_dp(wgt: list[int], val: list[int], cap: int) -> int:
"""Complete knapsack: Dynamic programming"""
n = len(wgt)
# Initialize dp table
dp = [[0] * (cap + 1) for _ in range(n + 1)]
# State transition
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
dp[i][c] = dp[i - 1][c]
else:
# The greater value between not choosing and choosing 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"""
n = len(wgt)
# Initialize dp table
dp = [0] * (cap + 1)
# State transition
for i in range(1, n + 1):
# Traverse in order
for c in range(1, cap + 1):
if wgt[i - 1] > c:
# If exceeding the knapsack capacity, do not choose item i
dp[c] = dp[c]
else:
# The greater value between not choosing and choosing item i
dp[c] = max(dp[c], dp[c - wgt[i - 1]] + val[i - 1])
return dp[cap]
"""Driver Code"""
if __name__ == "__main__":
wgt = [1, 2, 3]
val = [5, 11, 15]
cap = 4
# Dynamic programming
res = unbounded_knapsack_dp(wgt, val, cap)
print(f"The maximum item value without 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}")