mirror of
https://github.com/krahets/hello-algo.git
synced 2025-11-02 12:58:42 +08:00
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:
62
en/codes/python/chapter_backtracking/n_queens.py
Normal file
62
en/codes/python/chapter_backtracking/n_queens.py
Normal file
@ -0,0 +1,62 @@
|
||||
"""
|
||||
File: n_queens.py
|
||||
Created Time: 2023-04-26
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
|
||||
def backtrack(
|
||||
row: int,
|
||||
n: int,
|
||||
state: list[list[str]],
|
||||
res: list[list[list[str]]],
|
||||
cols: list[bool],
|
||||
diags1: list[bool],
|
||||
diags2: list[bool],
|
||||
):
|
||||
"""Backtracking algorithm: n queens"""
|
||||
# When all rows are placed, record the solution
|
||||
if row == n:
|
||||
res.append([list(row) for row in state])
|
||||
return
|
||||
# Traverse all columns
|
||||
for col in range(n):
|
||||
# Calculate the main and minor diagonals corresponding to the cell
|
||||
diag1 = row - col + n - 1
|
||||
diag2 = row + col
|
||||
# Pruning: do not allow queens on the column, main diagonal, or minor diagonal of the cell
|
||||
if not cols[col] and not diags1[diag1] and not diags2[diag2]:
|
||||
# Attempt: place the queen in the cell
|
||||
state[row][col] = "Q"
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = True
|
||||
# Place the next row
|
||||
backtrack(row + 1, n, state, res, cols, diags1, diags2)
|
||||
# Retract: restore the cell to an empty spot
|
||||
state[row][col] = "#"
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = False
|
||||
|
||||
|
||||
def n_queens(n: int) -> list[list[list[str]]]:
|
||||
"""Solve n queens"""
|
||||
# Initialize an n*n size chessboard, where 'Q' represents the queen and '#' represents an empty spot
|
||||
state = [["#" for _ in range(n)] for _ in range(n)]
|
||||
cols = [False] * n # Record columns with queens
|
||||
diags1 = [False] * (2 * n - 1) # Record main diagonals with queens
|
||||
diags2 = [False] * (2 * n - 1) # Record minor diagonals with queens
|
||||
res = []
|
||||
backtrack(0, n, state, res, cols, diags1, diags2)
|
||||
|
||||
return res
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
n = 4
|
||||
res = n_queens(n)
|
||||
|
||||
print(f"Input chessboard dimensions as {n}")
|
||||
print(f"The total number of queen placement solutions is {len(res)}")
|
||||
for state in res:
|
||||
print("--------------------")
|
||||
for row in state:
|
||||
print(row)
|
||||
44
en/codes/python/chapter_backtracking/permutations_i.py
Normal file
44
en/codes/python/chapter_backtracking/permutations_i.py
Normal file
@ -0,0 +1,44 @@
|
||||
"""
|
||||
File: permutations_i.py
|
||||
Created Time: 2023-04-15
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
|
||||
def backtrack(
|
||||
state: list[int], choices: list[int], selected: list[bool], res: list[list[int]]
|
||||
):
|
||||
"""Backtracking algorithm: Permutation I"""
|
||||
# When the state length equals the number of elements, record the solution
|
||||
if len(state) == len(choices):
|
||||
res.append(list(state))
|
||||
return
|
||||
# Traverse all choices
|
||||
for i, choice in enumerate(choices):
|
||||
# Pruning: do not allow repeated selection of elements
|
||||
if not selected[i]:
|
||||
# Attempt: make a choice, update the state
|
||||
selected[i] = True
|
||||
state.append(choice)
|
||||
# Proceed to the next round of selection
|
||||
backtrack(state, choices, selected, res)
|
||||
# Retract: undo the choice, restore to the previous state
|
||||
selected[i] = False
|
||||
state.pop()
|
||||
|
||||
|
||||
def permutations_i(nums: list[int]) -> list[list[int]]:
|
||||
"""Permutation I"""
|
||||
res = []
|
||||
backtrack(state=[], choices=nums, selected=[False] * len(nums), res=res)
|
||||
return res
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
nums = [1, 2, 3]
|
||||
|
||||
res = permutations_i(nums)
|
||||
|
||||
print(f"Input array nums = {nums}")
|
||||
print(f"All permutations res = {res}")
|
||||
46
en/codes/python/chapter_backtracking/permutations_ii.py
Normal file
46
en/codes/python/chapter_backtracking/permutations_ii.py
Normal file
@ -0,0 +1,46 @@
|
||||
"""
|
||||
File: permutations_ii.py
|
||||
Created Time: 2023-04-15
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
|
||||
def backtrack(
|
||||
state: list[int], choices: list[int], selected: list[bool], res: list[list[int]]
|
||||
):
|
||||
"""Backtracking algorithm: Permutation II"""
|
||||
# When the state length equals the number of elements, record the solution
|
||||
if len(state) == len(choices):
|
||||
res.append(list(state))
|
||||
return
|
||||
# Traverse all choices
|
||||
duplicated = set[int]()
|
||||
for i, choice in enumerate(choices):
|
||||
# Pruning: do not allow repeated selection of elements and do not allow repeated selection of equal elements
|
||||
if not selected[i] and choice not in duplicated:
|
||||
# Attempt: make a choice, update the state
|
||||
duplicated.add(choice) # Record selected element values
|
||||
selected[i] = True
|
||||
state.append(choice)
|
||||
# Proceed to the next round of selection
|
||||
backtrack(state, choices, selected, res)
|
||||
# Retract: undo the choice, restore to the previous state
|
||||
selected[i] = False
|
||||
state.pop()
|
||||
|
||||
|
||||
def permutations_ii(nums: list[int]) -> list[list[int]]:
|
||||
"""Permutation II"""
|
||||
res = []
|
||||
backtrack(state=[], choices=nums, selected=[False] * len(nums), res=res)
|
||||
return res
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
nums = [1, 2, 2]
|
||||
|
||||
res = permutations_ii(nums)
|
||||
|
||||
print(f"Input array nums = {nums}")
|
||||
print(f"All permutations res = {res}")
|
||||
@ -0,0 +1,36 @@
|
||||
"""
|
||||
File: preorder_traversal_i_compact.py
|
||||
Created Time: 2023-04-15
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.append(str(Path(__file__).parent.parent))
|
||||
from modules import TreeNode, print_tree, list_to_tree
|
||||
|
||||
|
||||
def pre_order(root: TreeNode):
|
||||
"""Pre-order traversal: Example one"""
|
||||
if root is None:
|
||||
return
|
||||
if root.val == 7:
|
||||
# Record solution
|
||||
res.append(root)
|
||||
pre_order(root.left)
|
||||
pre_order(root.right)
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
root = list_to_tree([1, 7, 3, 4, 5, 6, 7])
|
||||
print("\nInitialize binary tree")
|
||||
print_tree(root)
|
||||
|
||||
# Pre-order traversal
|
||||
res = list[TreeNode]()
|
||||
pre_order(root)
|
||||
|
||||
print("\nOutput all nodes with value 7")
|
||||
print([node.val for node in res])
|
||||
@ -0,0 +1,42 @@
|
||||
"""
|
||||
File: preorder_traversal_ii_compact.py
|
||||
Created Time: 2023-04-15
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.append(str(Path(__file__).parent.parent))
|
||||
from modules import TreeNode, print_tree, list_to_tree
|
||||
|
||||
|
||||
def pre_order(root: TreeNode):
|
||||
"""Pre-order traversal: Example two"""
|
||||
if root is None:
|
||||
return
|
||||
# Attempt
|
||||
path.append(root)
|
||||
if root.val == 7:
|
||||
# Record solution
|
||||
res.append(list(path))
|
||||
pre_order(root.left)
|
||||
pre_order(root.right)
|
||||
# Retract
|
||||
path.pop()
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
root = list_to_tree([1, 7, 3, 4, 5, 6, 7])
|
||||
print("\nInitialize binary tree")
|
||||
print_tree(root)
|
||||
|
||||
# Pre-order traversal
|
||||
path = list[TreeNode]()
|
||||
res = list[list[TreeNode]]()
|
||||
pre_order(root)
|
||||
|
||||
print("\nOutput all root-to-node 7 paths")
|
||||
for path in res:
|
||||
print([node.val for node in path])
|
||||
@ -0,0 +1,43 @@
|
||||
"""
|
||||
File: preorder_traversal_iii_compact.py
|
||||
Created Time: 2023-04-15
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.append(str(Path(__file__).parent.parent))
|
||||
from modules import TreeNode, print_tree, list_to_tree
|
||||
|
||||
|
||||
def pre_order(root: TreeNode):
|
||||
"""Pre-order traversal: Example three"""
|
||||
# Pruning
|
||||
if root is None or root.val == 3:
|
||||
return
|
||||
# Attempt
|
||||
path.append(root)
|
||||
if root.val == 7:
|
||||
# Record solution
|
||||
res.append(list(path))
|
||||
pre_order(root.left)
|
||||
pre_order(root.right)
|
||||
# Retract
|
||||
path.pop()
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
root = list_to_tree([1, 7, 3, 4, 5, 6, 7])
|
||||
print("\nInitialize binary tree")
|
||||
print_tree(root)
|
||||
|
||||
# Pre-order traversal
|
||||
path = list[TreeNode]()
|
||||
res = list[list[TreeNode]]()
|
||||
pre_order(root)
|
||||
|
||||
print("\nOutput all root-to-node 7 paths, not including nodes with value 3")
|
||||
for path in res:
|
||||
print([node.val for node in path])
|
||||
@ -0,0 +1,71 @@
|
||||
"""
|
||||
File: preorder_traversal_iii_template.py
|
||||
Created Time: 2023-04-15
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.append(str(Path(__file__).parent.parent))
|
||||
from modules import TreeNode, print_tree, list_to_tree
|
||||
|
||||
|
||||
def is_solution(state: list[TreeNode]) -> bool:
|
||||
"""Determine if the current state is a solution"""
|
||||
return state and state[-1].val == 7
|
||||
|
||||
|
||||
def record_solution(state: list[TreeNode], res: list[list[TreeNode]]):
|
||||
"""Record solution"""
|
||||
res.append(list(state))
|
||||
|
||||
|
||||
def is_valid(state: list[TreeNode], choice: TreeNode) -> bool:
|
||||
"""Determine if the choice is legal under the current state"""
|
||||
return choice is not None and choice.val != 3
|
||||
|
||||
|
||||
def make_choice(state: list[TreeNode], choice: TreeNode):
|
||||
"""Update state"""
|
||||
state.append(choice)
|
||||
|
||||
|
||||
def undo_choice(state: list[TreeNode], choice: TreeNode):
|
||||
"""Restore state"""
|
||||
state.pop()
|
||||
|
||||
|
||||
def backtrack(
|
||||
state: list[TreeNode], choices: list[TreeNode], res: list[list[TreeNode]]
|
||||
):
|
||||
"""Backtracking algorithm: Example three"""
|
||||
# Check if it's a solution
|
||||
if is_solution(state):
|
||||
# Record solution
|
||||
record_solution(state, res)
|
||||
# Traverse all choices
|
||||
for choice in choices:
|
||||
# Pruning: check if the choice is legal
|
||||
if is_valid(state, choice):
|
||||
# Attempt: make a choice, update the state
|
||||
make_choice(state, choice)
|
||||
# Proceed to the next round of selection
|
||||
backtrack(state, [choice.left, choice.right], res)
|
||||
# Retract: undo the choice, restore to the previous state
|
||||
undo_choice(state, choice)
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
root = list_to_tree([1, 7, 3, 4, 5, 6, 7])
|
||||
print("\nInitialize binary tree")
|
||||
print_tree(root)
|
||||
|
||||
# Backtracking algorithm
|
||||
res = []
|
||||
backtrack(state=[], choices=[root], res=res)
|
||||
|
||||
print("\nOutput all root-to-node 7 paths, requiring paths not to include nodes with value 3")
|
||||
for path in res:
|
||||
print([node.val for node in path])
|
||||
48
en/codes/python/chapter_backtracking/subset_sum_i.py
Normal file
48
en/codes/python/chapter_backtracking/subset_sum_i.py
Normal file
@ -0,0 +1,48 @@
|
||||
"""
|
||||
File: subset_sum_i.py
|
||||
Created Time: 2023-06-17
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
|
||||
def backtrack(
|
||||
state: list[int], target: int, choices: list[int], start: int, res: list[list[int]]
|
||||
):
|
||||
"""Backtracking algorithm: Subset Sum I"""
|
||||
# When the subset sum equals target, record the solution
|
||||
if target == 0:
|
||||
res.append(list(state))
|
||||
return
|
||||
# Traverse all choices
|
||||
# Pruning two: start traversing from start to avoid generating duplicate subsets
|
||||
for i in range(start, len(choices)):
|
||||
# Pruning one: if the subset sum exceeds target, end the loop immediately
|
||||
# This is because the array is sorted, and later elements are larger, so the subset sum will definitely exceed target
|
||||
if target - choices[i] < 0:
|
||||
break
|
||||
# Attempt: make a choice, update target, start
|
||||
state.append(choices[i])
|
||||
# Proceed to the next round of selection
|
||||
backtrack(state, target - choices[i], choices, i, res)
|
||||
# Retract: undo the choice, restore to the previous state
|
||||
state.pop()
|
||||
|
||||
|
||||
def subset_sum_i(nums: list[int], target: int) -> list[list[int]]:
|
||||
"""Solve Subset Sum I"""
|
||||
state = [] # State (subset)
|
||||
nums.sort() # Sort nums
|
||||
start = 0 # Start point for traversal
|
||||
res = [] # Result list (subset list)
|
||||
backtrack(state, target, nums, start, res)
|
||||
return res
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
nums = [3, 4, 5]
|
||||
target = 9
|
||||
res = subset_sum_i(nums, target)
|
||||
|
||||
print(f"Input array nums = {nums}, target = {target}")
|
||||
print(f"All subsets equal to {target} res = {res}")
|
||||
50
en/codes/python/chapter_backtracking/subset_sum_i_naive.py
Normal file
50
en/codes/python/chapter_backtracking/subset_sum_i_naive.py
Normal file
@ -0,0 +1,50 @@
|
||||
"""
|
||||
File: subset_sum_i_naive.py
|
||||
Created Time: 2023-06-17
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
|
||||
def backtrack(
|
||||
state: list[int],
|
||||
target: int,
|
||||
total: int,
|
||||
choices: list[int],
|
||||
res: list[list[int]],
|
||||
):
|
||||
"""Backtracking algorithm: Subset Sum I"""
|
||||
# When the subset sum equals target, record the solution
|
||||
if total == target:
|
||||
res.append(list(state))
|
||||
return
|
||||
# Traverse all choices
|
||||
for i in range(len(choices)):
|
||||
# Pruning: if the subset sum exceeds target, skip that choice
|
||||
if total + choices[i] > target:
|
||||
continue
|
||||
# Attempt: make a choice, update elements and total
|
||||
state.append(choices[i])
|
||||
# Proceed to the next round of selection
|
||||
backtrack(state, target, total + choices[i], choices, res)
|
||||
# Retract: undo the choice, restore to the previous state
|
||||
state.pop()
|
||||
|
||||
|
||||
def subset_sum_i_naive(nums: list[int], target: int) -> list[list[int]]:
|
||||
"""Solve Subset Sum I (including duplicate subsets)"""
|
||||
state = [] # State (subset)
|
||||
total = 0 # Subset sum
|
||||
res = [] # Result list (subset list)
|
||||
backtrack(state, target, total, nums, res)
|
||||
return res
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
nums = [3, 4, 5]
|
||||
target = 9
|
||||
res = subset_sum_i_naive(nums, target)
|
||||
|
||||
print(f"Input array nums = {nums}, target = {target}")
|
||||
print(f"All subsets equal to {target} res = {res}")
|
||||
print(f"Please note that the result of this method includes duplicate sets")
|
||||
52
en/codes/python/chapter_backtracking/subset_sum_ii.py
Normal file
52
en/codes/python/chapter_backtracking/subset_sum_ii.py
Normal file
@ -0,0 +1,52 @@
|
||||
"""
|
||||
File: subset_sum_ii.py
|
||||
Created Time: 2023-06-17
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
|
||||
def backtrack(
|
||||
state: list[int], target: int, choices: list[int], start: int, res: list[list[int]]
|
||||
):
|
||||
"""Backtracking algorithm: Subset Sum II"""
|
||||
# When the subset sum equals target, record the solution
|
||||
if target == 0:
|
||||
res.append(list(state))
|
||||
return
|
||||
# Traverse all choices
|
||||
# Pruning two: start traversing from start to avoid generating duplicate subsets
|
||||
# Pruning three: start traversing from start to avoid repeatedly selecting the same element
|
||||
for i in range(start, len(choices)):
|
||||
# Pruning one: if the subset sum exceeds target, end the loop immediately
|
||||
# This is because the array is sorted, and later elements are larger, so the subset sum will definitely exceed target
|
||||
if target - choices[i] < 0:
|
||||
break
|
||||
# Pruning four: if the element equals the left element, it indicates that the search branch is repeated, skip it
|
||||
if i > start and choices[i] == choices[i - 1]:
|
||||
continue
|
||||
# Attempt: make a choice, update target, start
|
||||
state.append(choices[i])
|
||||
# Proceed to the next round of selection
|
||||
backtrack(state, target - choices[i], choices, i + 1, res)
|
||||
# Retract: undo the choice, restore to the previous state
|
||||
state.pop()
|
||||
|
||||
|
||||
def subset_sum_ii(nums: list[int], target: int) -> list[list[int]]:
|
||||
"""Solve Subset Sum II"""
|
||||
state = [] # State (subset)
|
||||
nums.sort() # Sort nums
|
||||
start = 0 # Start point for traversal
|
||||
res = [] # Result list (subset list)
|
||||
backtrack(state, target, nums, start, res)
|
||||
return res
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
nums = [4, 4, 5]
|
||||
target = 9
|
||||
res = subset_sum_ii(nums, target)
|
||||
|
||||
print(f"Input array nums = {nums}, target = {target}")
|
||||
print(f"All subsets equal to {target} res = {res}")
|
||||
Reference in New Issue
Block a user