40. Combination Sum II

每日一题 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
2
3
4
5
6
7
8
Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]

Example 2:

1
2
3
4
5
6
Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
[1,2,2],
[5]
]

解法:

这个题让我们在给定数组里面找到不重复的序列的和等于给定的值,跟昨天的sum I不同的地方在于这个题元素不可重复,那个题是可重复的,所以思路还是回溯,不过为了保证输出元素的有序性,可以先把 candidates 中得元素先 sort 一下,还有一个需要注意的地方就是可能res中存放的元素有重复的,所以就在pushres进去之前,先遍历一遍res看是否存在重复的序列,或者使用set


代码:

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
class Solution {
public:
vector<vector<int>>res;
vector<int>ans;
int nums_len;

vector<vector<int> > combinationSum2(vector<int> &candidates, int target) {
sort(candidates.begin(),candidates.end());
if(candidates.empty()) return res;
nums_len = candidates.size();
dfs(0, 0, target, candidates);
return res;
}

void dfs(int start, int sum, int target,vector<int> candidates){
if(sum == target) {
if(res.end() != find(res.begin(),res.end(),ans))
{
return ;
}
res.push_back(ans); return; }
else if(sum > target)
return;
else{
for(int i = start; i < nums_len ; i++){
ans.push_back(candidates[i]);
dfs(i + 1, sum + candidates[i], target, candidates);
ans.pop_back();
}
}
}
};
0%
undefined