题目描述
给定一个无重复元素的数组 candidates
和一个目标数 target
,找出 candidates
中所有可以使数字和为 target
的组合。
candidates
中的数字可以无限制重复被选取。
说明:
- 所有数字(包括
target
)都是正整数。 - 解集不能包含重复的组合。
样例
输入: candidates = [2,3,6,7], target = 7,
所求解集为:[
[7],
[2,2,3]
]
输入: candidates = [2,3,5], target = 8,
所求解集为:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
思路分析
基本思路:dfs递归,需要注意两点,一是递归之后的剪枝,二是要先排序再递归(提高效率)
代码及结果
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
List<Integer> list1 = new ArrayList<Integer>();
Arrays.sort(candidates);
dfs(candidates, 0, target, list, list1);
return list;
}
void dfs(int[] candidates, int start, int target, List<List<Integer>> list, List<Integer> list1){
if (target < 0) {
return;
}
else if (target == 0) {
list.add(new ArrayList<Integer>(list1));
}
else {
for (int i = start; i < candidates.length; i++) {
list1.add(candidates[i]);
dfs(candidates, i, target-candidates[i], list, list1);
list1.remove(list1.size()-1);
}
}
}