Files
hello-algo/ja/codes/python/chapter_backtracking/subset_sum_i_naive.py
T
Yudong Jin 7257641e0e Retranslate the complete Japanese online edition from Chinese (#2008)
* Retranslate the complete Japanese online edition from Chinese

* Fit Japanese homepage labels and localize heading permalinks

* Point Japanese contribution instructions to the Japanese preview

* Replace locale conditionals with multilingual UI tables
2026-10-30 02:12:26 +08:00

51 lines
1.6 KiB
Python

"""
File: subset_sum_i_naive.py
Created Time: 2023-06-17
Author: krahets ([email protected])
"""
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"この方法の出力結果には重複した集合が含まれることに注意")