leetcode解题: Combination Sum II (40)

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, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]

解法1:

这题和Combination Sum的唯一区别是每一个数字只能使用一次,那么每一次挑选的时候无论是否有解都往前进一格就可以了。
C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int>> res;
vector<int> current;
sort(candidates.begin(),candidates.end());
backTracking(candidates.begin(),current,res,candidates,target);
return res;
}
void backTracking(vector<int>::iterator n, vector<int>& current,vector<vector<int>>& res, const vector<int>& candidates, int target){
if(!target) res.push_back(current);
else if(target>0){
for(;n!=candidates.end()&&*n<=target;++n){
current.push_back(*n);
backTracking(n+1,current,res,candidates,target-*n);
current.pop_back();
while(n+1!=candidates.end()&&*(n+1)==*n) ++n;
}
}
}
};

Java

1