Leetcode练习(Python):数组类:第40题:给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的每个数字在每个组合中只能使用一次。
题目:
给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。
说明:
所有数字(包括目标数)都是正整数。
解集不能包含重复的组合。
思路:总体思路和第39题一样,但是在每个数字只能使用一次的条件下,需要进行第二次剪枝。
程序:
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
length = len(candidates)
if length <= 0:
return []
result = []
temp_result = []
def auxiliary(index, temp_result, target):
if target == 0:
result.append(temp_result)
return
if index == length or target < candidates[index]:
return
for temp_index in range(index, length):
if temp_index > index and candidates[temp_index] == candidates[temp_index - 1]:
continue
auxiliary(temp_index + 1, temp_result + [candidates[temp_index]], target - candidates[temp_index])
auxiliary(0, temp_result, target)
return result