LeetCode | 0040. Combination Sum II組合總和 II【Python】
阿新 • • 發佈:2020-09-10
Problem
Given a collection of candidate numbers (candidates
) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
Each number in candidates
may only be used once in the combination.
Note:
- All numbers (including
target
) will be positive integers. - The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
[1,2,2],
[5]
]
問題
給定一個數組 candidates 和一個目標數 target ,找出 candidates 中所有可以使數字和為 target 的組合。
candidates 中的每個數字在每個組合中只能使用一次。
說明:
- 所有數字(包括目標數)都是正整數。
- 解集不能包含重複的組合。
示例 1:
輸入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集為:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
示例 2:
輸入: candidates = [2,5,2,1,2], target = 5,
所求解集為:
[
[1,2,2],
[5]
]
思路
回溯模板
res = [] def backtrack(路徑, 選擇列表): if 滿足結束條件: res.append(路徑) return for 選擇 in 選擇列表: 做選擇 backtrack(路徑, 選擇列表) 撤銷選擇
Python3 程式碼
from typing import List
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
n = len(candidates)
if n == 0:
return []
# accelerate 剪枝提速,非必需
candidates.sort()
path, res = [], []
self.dfs(candidates, 0, n, path, res, target)
return res
def dfs(self, candidates, start, n, path, res, target):
# 1.valid result 遞迴終止情況
if target == 0:
res.append(path[:])
return
for i in range(start, n):
tmp = target - candidates[i]
# 3.pruning 剪枝
if tmp < 0:
break
# 防止出現這種情況:一個數字使用多次
if i > start and candidates[i] == candidates[i - 1]:
continue
# 2.backtrack and update 回溯以及更新 path
path.append(candidates[i])
self.dfs(candidates, i + 1, n, path, res, tmp)
path.pop()