组合总和
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
说明:
- 所有数字(包括 target)都是正整数。
- 解集不能包含重复的组合。
示例 1:
输入: candidates = [2,3,6,7], target = 7,
所求解集为:
[
[7],
[2,2,3]
]
思路+代码+注释:
public static List<List<Integer>> combinationSum(int[] candidates, int target) {
/*
思路:将查找数字组合拆分成两个子问题——第一个数和查找组合剩余的数,大问题的解就是将两个小问题的
结果放在一个out集合中。
找到第一个数后递归往后查找数字组合,剩余数是从第一个数的位置开始继续找(因为可以重复)。
递归终止条件:当目标值小于0时,就不用找了;当目标值等于0时,组合符合条件添加到结果中
*/
//对数组排序
Arrays.sort(candidates);
List<Integer> out=new LinkedList<>();
List<List<Integer>> resource=new LinkedList<List<Integer>>();
findOneNum(candidates,0,target,out,resource);
return resource;
}
//start数字开始查找的位置
private static void findOneNum(int[] candidates,int start,int target,List<Integer> out,List<List<Integer>> resource)
{
if (target<0)
{
return;
}else if (target==0)
{
resource.add(new ArrayList<Integer>(out));
return;
}
for (int i = start; i < candidates.length; i++) {
out.add(candidates[i]);
findOneNum(candidates,i,target-candidates[i],out,resource);
//查找到下一个数后将该数从out中移除,避免找下一个组合时前一个组合的数仍然在out中
out.remove(out.size()-1);
}
}