leetcode-40-Combination-Sum-II

描述


Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C 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.

For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,

A solution set is:

1
2
3
4
5
6
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]

分析


这道题和 leetcode-39-Combination-Sum基本是一样的,只是这一题要求 candidates 中的内容不能重复出现,只需要修改两处代码。

解决方案1(C++)


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
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<vector<int>> result;
vector<int> path;
dfs(candidates, path, result, target, 0);
return result;
}

private:
void dfs(vector<int>& candidates, vector<int>& path, vector<vector<int>>& result, int target, int start) {
if(target == 0) {
result.push_back(path);
return;
}

for(int i = start; i < candidates.size(); i++) {
if(i>start && candidates[i] == candidates[i-1]) {
continue;
}
if(candidates[i] > target) {
return;
}
path.push_back(candidates[i]);
dfs(candidates, path, result, target-candidates[i], i+1);
path.pop_back();
}
}
};

解决方案2(Python)


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
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
result = []
path = []
self.dfs(candidates, path, result, target)
return result

def dfs(self, candidates, path, result, target):
if target == 0:
result.append(path[:])
return
pre = None
for item, value in enumerate(candidates):
if pre is None or pre != value:
if target < value:
return
path.append(value)
self.dfs(candidates[item+1:], path, result, target-value)
path.pop()
pre = value

相关问题


题目来源