问题描述
Given a set of candidate numbers ( C ) 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.
Elements in a combination (a 1, a 2, … , a k) must be in non-descending order. (ie, a 1 ≤ a 2 ≤ … ≤ a k).
The solution set must not contain duplicate combinations.For example, given candidate set2,3,6,7and target7,
A solution set is:
[7]
[2, 2, 3]
问题分析
这题考察的回溯法点的应用,由于可以存在相同的数,所以回溯还是从i开始,具体实现看代码就行了。基本上像这种列举解的算法都是用回溯+递归进行的。没有什么额外的难度。
代码实现
public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
ArrayList<Integer> list = new ArrayList<>();
backTrackingSum(candidates, 0, target, list, result);
return result;
}
private void backTrackingSum(int[] cadidates, int start, int target, ArrayList<Integer> list,
ArrayList<ArrayList<Integer>> result) {
if (target == 0) {
result.add(new ArrayList<Integer>(list));
return;
} else {
for (int i = start; i < cadidates.length && cadidates[i] <= target; i++) {
list.add(cadidates[i]);
backTrackingSum(cadidates, i, target - cadidates[i], list, result);
list.remove(list.size() - 1);
}
}
}
网友评论