Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7]
and target 7,
A solution set is:
[
[7],
[2, 2, 3]
]
题意:给我们一个数组,我们需要将数组中任意的数字组合(可以重复)相加结果等于给我们的target,我们要将所有可能的组合记录下来。
java代码:
public List<List<Integer>> combinationSum(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);
current.remove(current.size() - 1);
}
} else if (target == 0) {
result.add(new ArrayList<Integer>(current));
}
}