Skip to content

Commit ac88c8d

Browse files
committed
40. Combination Sum II
1 parent 8961be9 commit ac88c8d

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Backtracking/combination_sum_2.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# Given a collection of candidate numbers (candidates) and a target number (target),
2+
# find all unique combinations in candidates where the candidate numbers sum to target.
3+
4+
# Each number in candidates may only be used once in the combination.
5+
6+
# Note: The solution set must not contain duplicate combinations.
7+
8+
# Example 1:
9+
# Input: candidates = [10,1,2,7,6,1,5], target = 8
10+
# Output:
11+
# [
12+
# [1,1,6],
13+
# [1,2,5],
14+
# [1,7],
15+
# [2,6]
16+
# ]
17+
18+
# Example 2:
19+
# Input: candidates = [2,5,2,1,2], target = 5
20+
# Output:
21+
# [
22+
# [1,2,2],
23+
# [5]
24+
# ]
25+
26+
27+
# Constraints:
28+
29+
# 1 <= candidates.length <= 100
30+
# 1 <= candidates[i] <= 50
31+
# 1 <= target <= 30
32+
33+
34+
from typing import List
35+
class Solution:
36+
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
37+
ans = []
38+
def dfs(s, t, path):
39+
if t < 0:
40+
return
41+
if t == 0:
42+
ans.append(path.copy())
43+
return
44+
for i in range(s, len(candidates)):
45+
if i > s and candidates[i] == candidates[i - 1]:
46+
continue
47+
path.append(candidates[i])
48+
dfs(i + 1, t - candidates[i], path)
49+
path.pop()
50+
candidates.sort()
51+
dfs(0, target, [])
52+
return ans

0 commit comments

Comments
 (0)