-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path40.组合总和-ii.py
43 lines (38 loc) · 1.19 KB
/
40.组合总和-ii.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#
# @lc app=leetcode.cn id=40 lang=python3
#
# [40] 组合总和 II
#
# %%
# @lc code=start
class Solution:
def combinationSum2(self, candidates, target):
# 将数组进行升序排序
candidates.sort()
# 结果列表
ans = []
# 可能组合
tmp = []
def helper(idx, total):
if total == target:
ans.append(tmp[::])
return
if total > target:
return
for i in range(idx, len(candidates)):
# 这里限制同一层不能选择值相同的元素
# 若有相同的元素,优先选择索引靠前的
if candidates[i-1] == candidates[i] and i-1 >= idx:
continue
total += candidates[i]
tmp.append(candidates[i])
# 这里注意,与 39 题不同,进入递归下一层
# 从当前索引的下一位开始选取,避免重复选取同个元素
helper(i+1, total)
# 回溯
tmp.pop()
total -= candidates[i]
total = 0
helper(0, total)
return ans
# @lc code=end