转载自:https://www.unclegem.cn/2018/09/10/Leetcode学习笔记-39-组合总和/
题目:
给定一个无重复元素的数组 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]
]
解题思路:
回溯:只要当前总和值小于目标值,就一直添加当前元素,添加到大于目标值,则回退到上一个状态去寻找下一个元素,其中的start参数是为了防止出现重复答案如[2,2,3]和[3,2,2]。
public int sum = 0;
public List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] c, int tar) {
res.clear();
sum = 0;
Arrays.sort(c);
List<Integer> list = new ArrayList<Integer>();
recycle(c, tar, list, sum, 0);
return res;
}
public void recycle(int[] c, int tar, List<Integer> list, int sum, int start) {//start记录当前元素的位置
if(sum == tar) {
res.add(new ArrayList<Integer>(list));
return;
}
for(int i = start; i< c.length; i++) {
if(sum < tar && (sum + c[i]) <= tar) {
list.add(c[i]);
sum += c[i];
recycle(c, tar, list, sum, i);//递归调用,其中的i参数是为了防止出现重复答案如[2,2,3]和[3,2,2]。
start ++;
sum -= c[i];//开始回溯到上一个状态
list.remove(list.size() - 1);
}
}
}
leetcode战胜30%左右,应该还有时间更少的解法,但对我来说这可能是一种比较容易想到的解法