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]
]
題意:這題和上一題39題,簡直一模一樣,那道題是可以重復(fù)的應(yīng)用同一個(gè)位置的數(shù)字,這題是不允許重復(fù)的應(yīng)用同一個(gè)位置的數(shù)字。
只需要在上一題的基礎(chǔ)上,遞歸的時(shí)候每次都大1,即不能等于本身就可以了。
java代碼:
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> result = new ArrayList<List<Integer>>();
getResult(result, new ArrayList<Integer>(), candidates, target, 0);
return result;
}
public void getResult(List<List<Integer>> result, List<Integer> current, int[] candiates, int target, int start) {
if (target > 0) {
for (int i = start; i < candiates.length && target >= candiates[i]; i++) {
current.add(candiates[i]);
getResult(result, current, candiates, target - candiates[i], i + 1);
current.remove(current.size() - 1);
}
} else if (target == 0) {
if (!result.contains(current)) {
result.add(new ArrayList<Integer>(current));
}
}
}