每日一题 2019 - 03 - 27
题目:
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
Each number in candidates may only be used once in the combination.
Note:
- All numbers (including target) will be positive integers.
- The solution set must not contain duplicate combinations.
Example 1:
| 1 | Input: candidates = [10,1,2,7,6,1,5], target = 8, | 
Example 2:
| 1 | Input: candidates = [2,5,2,1,2], target = 5, | 
解法:
这个题让我们在给定数组里面找到不重复的序列的和等于给定的值,跟昨天的sum I不同的地方在于这个题元素不可重复,那个题是可重复的,所以思路还是回溯,不过为了保证输出元素的有序性,可以先把 candidates 中得元素先 sort 一下,还有一个需要注意的地方就是可能res中存放的元素有重复的,所以就在push到res进去之前,先遍历一遍res看是否存在重复的序列,或者使用set
代码:
| 1 | class Solution { |