descirption:
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]
]
解题思路:
这一问题与subset ii的问题基本是同一问题,就是加了一个target用于控制循环的次数。
subset ii的问题主要是一个选代表的问题,也就是相同的数字只用第一个,后面的数字是不去要使用的,这也就是涉及到了一个选代表的过程。
public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> list = new ArrayList<>();
if (candidates == null || candidates.length == 0) {
return result;
}
Arrays.sort(candidates);
util(candidates, 0, target, result, list);
return result;
}
private void util(int[] candidates,
int start,
int remind,
List<List<Integer>> result,
List<Integer> list) {
if (remind == 0) {
result.add(new ArrayList<Integer>(list));
return;
}
for (int i = start; i < candidates.length; i++) {
if (candidates[i] > remind) {
break;
}
if (i != start && candidates[i] == candidates[i - 1]) {
continue;
}
list.add(candidates[i]);
util(candidates, i + 1, remind - candidates[i], result, list);
list.remove(list.size() - 1);
}
}
}