问题描述:
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
说明:
所有数字(包括 target)都是正整数。
解集不能包含重复的组合。
示例 1:
输入:candidates = [2,3,6,7], target = 7,
所求解集为:
[
[7],
[2,2,3]
]
示例 2:
输入:candidates = [2,3,5], target = 8,
所求解集为:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
提示:
- 1 <= candidates.length <= 30
- 1 <= candidates[i] <= 200
- candidate 中的每个元素都是独一无二的。
- 1 <= target <= 500
解题思路:
需要注意的是每个元素可以重复使用,所以不能通过生成所有子集的方法进行求解。可以使用深搜的方式进行求解。
参考文章
代码实现:
import java.util.*;
public class test39组合总和 {
List<List<Integer>> res = new LinkedList<List<Integer>>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
LinkedList<Integer> list = new LinkedList<>();
Arrays.sort(candidates);
dfs(list, candidates, target, 0);
return res;
}
/**
* 为了避免集合重复,需要添加一个起点参数,每次从起点开始进行选择、
* 因为数组中每个元素都是不同的,所以这样就不会出现两个集合相同的情况
* 由于有起点参数的限制,深搜越往下时,分支越少;可以提高效率
*/
private void dfs(LinkedList<Integer> list, int[] arr,int target, int begin) {
if(target<0){
return;
}
if(target==0){
res.add(new LinkedList<Integer>(list));
return;
}
for(int i=begin; i<arr.length; i++){
list.add(arr[i]);
// 注意:由于每一个元素可以重复使用,下一轮搜索的起点依然是 i
dfs(list, arr, target-arr[i], i);
//回溯
list.removeLast();
}
}
}
提交结果: