Combination Sum
Given a set of candidate numbers (
candidates
) (without duplicates) and a target number (target
), find all unique combinations incandidates
where the candidate numbers sums totarget
.The same repeated number may be chosen from
candidates
unlimited number of times.Note:
- All numbers (including
target
) will be positive integers.- The solution set must not contain duplicate combinations.
Example 1
1 | Input: candidates = [2,3,6,7], target = 7, |
Example 2
1 | Input: candidates = [2,3,5], target = 8, |
解题思路
回溯法。对于每一层,若 target<0
,表示该组合不可行,直接返回上一层。若 target==0
,说明得到可行组合,将其加入结果集并返回上一层。若 target>0
,将其减去当前元素,并递归求解子问题。为避免加入重复组合,在求解子问题时不考虑之前元素。
复杂度分析
略(不会)。
代码
1 | class Solution { |