feat(ko): add the Korean online edition (#2006)

* feat(ko): add the complete Korean online edition

* Use UTF-8 for Python CI output on Windows

* Remove print-book promotion from the Korean site

* fix(ko): preserve emphasis before Korean particles
This commit is contained in:
Yudong Jin
2026-10-29 03:46:43 +08:00
committed by GitHub
parent 71a773df64
commit 2f561d3d51
2072 changed files with 110884 additions and 102 deletions
@@ -0,0 +1,62 @@
"""
File: n_queens.py
Created Time: 2023-04-26
Author: krahets ([email protected])
"""
def backtrack(
row: int,
n: int,
state: list[list[str]],
res: list[list[list[str]]],
cols: list[bool],
diags1: list[bool],
diags2: list[bool],
):
"""백트래킹 알고리즘: n-퀸"""
# 모든 행에 배치했으면 해를 기록한다
if row == n:
res.append([list(row) for row in state])
return
# 모든 열을 순회한다
for col in range(n):
# 해당 칸이 속한 주대각선과 부대각선을 계산한다
diag1 = row - col + n - 1
diag2 = row + col
# 가지치기: 해당 칸이 속한 열, 주대각선, 부대각선에 퀸이 있으면 안 된다
if not cols[col] and not diags1[diag1] and not diags2[diag2]:
# 시도: 해당 칸에 퀸을 놓는다
state[row][col] = "Q"
cols[col] = diags1[diag1] = diags2[diag2] = True
# 다음 행에 배치한다
backtrack(row + 1, n, state, res, cols, diags1, diags2)
# 되돌리기: 해당 칸을 빈칸으로 되돌린다
state[row][col] = "#"
cols[col] = diags1[diag1] = diags2[diag2] = False
def n_queens(n: int) -> list[list[list[str]]]:
"""n-퀸 문제 풀기"""
# n*n 크기의 체스판을 초기화한다. 'Q'는 퀸, '#'은 빈칸을 나타낸다
state = [["#" for _ in range(n)] for _ in range(n)]
cols = [False] * n # 열에 퀸이 있는지 기록한다
diags1 = [False] * (2 * n - 1) # 주대각선에 퀸이 있는지 기록한다
diags2 = [False] * (2 * n - 1) # 부대각선에 퀸이 있는지 기록한다
res = []
backtrack(0, n, state, res, cols, diags1, diags2)
return res
"""실행 코드"""
if __name__ == "__main__":
n = 4
res = n_queens(n)
print(f"입력한 체스판의 가로와 세로 길이: {n}")
print(f"퀸을 배치하는 방법은 총 {len(res)}가지이다")
for state in res:
print("--------------------")
for row in state:
print(row)
@@ -0,0 +1,44 @@
"""
File: permutations_i.py
Created Time: 2023-04-15
Author: krahets ([email protected])
"""
def backtrack(
state: list[int], choices: list[int], selected: list[bool], res: list[list[int]]
):
"""백트래킹 알고리즘: 모든 순열 I"""
# 상태의 길이가 원소 개수와 같으면 해를 기록한다
if len(state) == len(choices):
res.append(list(state))
return
# 모든 선택지를 순회한다
for i, choice in enumerate(choices):
# 가지치기: 원소를 중복하여 선택할 수 없다
if not selected[i]:
# 시도: 선택하고 상태를 갱신한다
selected[i] = True
state.append(choice)
# 다음 선택을 진행한다
backtrack(state, choices, selected, res)
# 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
selected[i] = False
state.pop()
def permutations_i(nums: list[int]) -> list[list[int]]:
"""모든 순열 I"""
res = []
backtrack(state=[], choices=nums, selected=[False] * len(nums), res=res)
return res
"""실행 코드"""
if __name__ == "__main__":
nums = [1, 2, 3]
res = permutations_i(nums)
print(f"입력 배열 nums = {nums}")
print(f"모든 순열 res = {res}")
@@ -0,0 +1,46 @@
"""
File: permutations_ii.py
Created Time: 2023-04-15
Author: krahets ([email protected])
"""
def backtrack(
state: list[int], choices: list[int], selected: list[bool], res: list[list[int]]
):
"""백트래킹 알고리즘: 모든 순열 II"""
# 상태의 길이가 원소 개수와 같으면 해를 기록한다
if len(state) == len(choices):
res.append(list(state))
return
# 모든 선택지를 순회한다
duplicated = set[int]()
for i, choice in enumerate(choices):
# 가지치기: 원소를 중복하여 선택할 수 없으며, 값이 같은 원소도 중복하여 선택할 수 없다
if not selected[i] and choice not in duplicated:
# 시도: 선택하고 상태를 갱신한다
duplicated.add(choice) # 선택한 원소의 값을 기록한다
selected[i] = True
state.append(choice)
# 다음 선택을 진행한다
backtrack(state, choices, selected, res)
# 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
selected[i] = False
state.pop()
def permutations_ii(nums: list[int]) -> list[list[int]]:
"""모든 순열 II"""
res = []
backtrack(state=[], choices=nums, selected=[False] * len(nums), res=res)
return res
"""실행 코드"""
if __name__ == "__main__":
nums = [1, 2, 2]
res = permutations_ii(nums)
print(f"입력 배열 nums = {nums}")
print(f"모든 순열 res = {res}")
@@ -0,0 +1,36 @@
"""
File: preorder_traversal_i_compact.py
Created Time: 2023-04-15
Author: krahets ([email protected])
"""
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):
"""전위 순회: 예제 1"""
if root is None:
return
if root.val == 7:
# 해를 기록한다
res.append(root)
pre_order(root.left)
pre_order(root.right)
"""실행 코드"""
if __name__ == "__main__":
root = list_to_tree([1, 7, 3, 4, 5, 6, 7])
print("\n이진 트리 초기화")
print_tree(root)
# 전위 순회
res = list[TreeNode]()
pre_order(root)
print("\n값이 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 ([email protected])
"""
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):
"""전위 순회: 예제 2"""
if root is None:
return
# 시도
path.append(root)
if root.val == 7:
# 해를 기록한다
res.append(list(path))
pre_order(root.left)
pre_order(root.right)
# 되돌리기
path.pop()
"""실행 코드"""
if __name__ == "__main__":
root = list_to_tree([1, 7, 3, 4, 5, 6, 7])
print("\n이진 트리 초기화")
print_tree(root)
# 전위 순회
path = list[TreeNode]()
res = list[list[TreeNode]]()
pre_order(root)
print("\n루트 노드에서 노드 7까지의 모든 경로 출력")
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 ([email protected])
"""
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):
"""전위 순회: 예제 3"""
# 가지치기
if root is None or root.val == 3:
return
# 시도
path.append(root)
if root.val == 7:
# 해를 기록한다
res.append(list(path))
pre_order(root.left)
pre_order(root.right)
# 되돌리기
path.pop()
"""실행 코드"""
if __name__ == "__main__":
root = list_to_tree([1, 7, 3, 4, 5, 6, 7])
print("\n이진 트리 초기화")
print_tree(root)
# 전위 순회
path = list[TreeNode]()
res = list[list[TreeNode]]()
pre_order(root)
print("\n루트 노드에서 노드 7까지의 모든 경로 출력. 경로에는 값이 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:
"""현재 상태가 해인지 판단"""
return state and state[-1].val == 7
def record_solution(state: list[TreeNode], res: list[list[TreeNode]]):
"""해를 기록한다"""
res.append(list(state))
def is_valid(state: list[TreeNode], choice: TreeNode) -> bool:
"""현재 상태에서 해당 선택이 유효한지 판단"""
return choice is not None and choice.val != 3
def make_choice(state: list[TreeNode], choice: TreeNode):
"""상태 갱신"""
state.append(choice)
def undo_choice(state: list[TreeNode], choice: TreeNode):
"""상태 복원"""
state.pop()
def backtrack(
state: list[TreeNode], choices: list[TreeNode], res: list[list[TreeNode]]
):
"""백트래킹 알고리즘: 예제 3"""
# 해인지 확인한다
if is_solution(state):
# 해를 기록한다
record_solution(state, res)
# 모든 선택지를 순회한다
for choice in choices:
# 가지치기: 선택이 유효한지 확인한다
if is_valid(state, choice):
# 시도: 선택하고 상태를 갱신한다
make_choice(state, choice)
# 다음 선택을 진행한다
backtrack(state, [choice.left, choice.right], res)
# 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
undo_choice(state, choice)
"""실행 코드"""
if __name__ == "__main__":
root = list_to_tree([1, 7, 3, 4, 5, 6, 7])
print("\n이진 트리 초기화")
print_tree(root)
# 백트래킹 알고리즘
res = []
backtrack(state=[], choices=[root], res=res)
print("\n값이 3인 노드를 포함하지 않는 조건으로, 루트 노드에서 노드 7까지의 모든 경로 출력")
for path in res:
print([node.val for node in path])
@@ -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]]
):
"""백트래킹 알고리즘: 부분 집합 합 I"""
# 부분 집합의 합이 target과 같으면 해를 기록한다
if target == 0:
res.append(list(state))
return
# 모든 선택지를 순회한다
# 가지치기 2: start부터 순회하여 중복 부분 집합 생성을 방지한다
for i in range(start, len(choices)):
# 가지치기 1: 부분 집합의 합이 target을 초과하면 즉시 반복문을 종료한다
# 배열이 정렬되어 있어 뒤의 원소가 더 크므로, 부분 집합의 합이 반드시 target을 초과하기 때문이다
if target - choices[i] < 0:
break
# 시도: 선택하고 target, start를 갱신한다
state.append(choices[i])
# 다음 선택을 진행한다
backtrack(state, target - choices[i], choices, i, res)
# 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
state.pop()
def subset_sum_i(nums: list[int], target: int) -> list[list[int]]:
"""부분 집합 합 I 풀기"""
state = [] # 상태(부분 집합)
nums.sort() # nums를 정렬한다
start = 0 # 순회 시작 위치
res = [] # 결과 리스트(부분 집합 리스트)
backtrack(state, target, nums, start, res)
return res
"""실행 코드"""
if __name__ == "__main__":
nums = [3, 4, 5]
target = 9
res = subset_sum_i(nums, target)
print(f"입력 배열 nums = {nums}, target = {target}")
print(f"합이 {target}인 모든 부분 집합 res = {res}")
@@ -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]],
):
"""백트래킹 알고리즘: 부분 집합 합 I"""
# 부분 집합의 합이 target과 같으면 해를 기록한다
if total == target:
res.append(list(state))
return
# 모든 선택지를 순회한다
for i in range(len(choices)):
# 가지치기: 부분 집합의 합이 target을 초과하면 해당 선택을 건너뛴다
if total + choices[i] > target:
continue
# 시도: 선택하고 원소의 합 total을 갱신한다
state.append(choices[i])
# 다음 선택을 진행한다
backtrack(state, target, total + choices[i], choices, res)
# 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
state.pop()
def subset_sum_i_naive(nums: list[int], target: int) -> list[list[int]]:
"""부분 집합 합 I 풀기(중복 부분 집합 포함)"""
state = [] # 상태(부분 집합)
total = 0 # 부분 집합의 합
res = [] # 결과 리스트(부분 집합 리스트)
backtrack(state, target, total, nums, res)
return res
"""실행 코드"""
if __name__ == "__main__":
nums = [3, 4, 5]
target = 9
res = subset_sum_i_naive(nums, target)
print(f"입력 배열 nums = {nums}, target = {target}")
print(f"합이 {target}인 모든 부분 집합 res = {res}")
print(f"이 방법의 출력 결과에는 중복 집합이 포함된다")
@@ -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]]
):
"""백트래킹 알고리즘: 부분 집합 합 II"""
# 부분 집합의 합이 target과 같으면 해를 기록한다
if target == 0:
res.append(list(state))
return
# 모든 선택지를 순회한다
# 가지치기 2: start부터 순회하여 중복 부분 집합 생성을 방지한다
# 가지치기 3: start부터 순회하여 같은 원소의 중복 선택을 방지한다
for i in range(start, len(choices)):
# 가지치기 1: 부분 집합의 합이 target을 초과하면 즉시 반복문을 종료한다
# 배열이 정렬되어 있어 뒤의 원소가 더 크므로, 부분 집합의 합이 반드시 target을 초과하기 때문이다
if target - choices[i] < 0:
break
# 가지치기 4: 해당 원소가 왼쪽 원소와 같으면 탐색 분기가 중복되므로 바로 건너뛴다
if i > start and choices[i] == choices[i - 1]:
continue
# 시도: 선택하고 target, start를 갱신한다
state.append(choices[i])
# 다음 선택을 진행한다
backtrack(state, target - choices[i], choices, i + 1, res)
# 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
state.pop()
def subset_sum_ii(nums: list[int], target: int) -> list[list[int]]:
"""부분 집합 합 II 풀기"""
state = [] # 상태(부분 집합)
nums.sort() # nums를 정렬한다
start = 0 # 순회 시작 위치
res = [] # 결과 리스트(부분 집합 리스트)
backtrack(state, target, nums, start, res)
return res
"""실행 코드"""
if __name__ == "__main__":
nums = [4, 4, 5]
target = 9
res = subset_sum_ii(nums, target)
print(f"입력 배열 nums = {nums}, target = {target}")
print(f"합이 {target}인 모든 부분 집합 res = {res}")