Given a collection of candidate numbers (
candidates
) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sum to target
.Each number in
candidates
may only be used once in the combination.Note: The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8
Output:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5
Output:
[
[1,2,2],
[5]
]
Constraints:
1 <= candidates.length <= 100
1 <= candidates[i] <= 50
*
1 <= target <= 30
题目大意:
求组合和等于目标。元素不可复用且结果去重
解题思路:
用组合模板,先排序
解题步骤:
N/A
注意事项:
- 类似于Leetcode 39,有两点不同。要去重,i > start并不是i > 0, 且比较前一个元素
- 因为元素不可重复,下一轮递归i + 1
Python代码:
1 | def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: |
算法分析:
时间复杂度为O(2n)
,空间复杂度O(n)