- 题目:给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
说明:
所有数字(包括 target)都是正整数。
解集不能包含重复的组合。
示例:输入:candidates = [2,3,6,7], target = 7,
所求解集为:
[
[7],
[2,2,3]
]
- 回溯+剪枝
剪枝的目的一是为了减少递归的次数,还要对得到的结果进行去重
List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target){
// Arrays.sort(candidates);
ArrayList<Integer> temp = new ArrayList<>();
recur(candidates, target, 0, temp);
return result;
}
public void recur(int[] candidates, int target, int left, List<Integer> temp){
if (left >= candidates.length || target < 0)
return;
if (target == 0){
List<Integer> list = new ArrayList<>(temp);
result.add(list);
return;
}
for (int i = left; i < candidates.length; i++){
temp.add(candidates[i]);
recur(candidates, target - candidates[i], i, temp);
temp.remove(temp.size() - 1);
}
}