Combination Sum
问题简介:给定一个数组(没有重复元素)和一个目标值,找到数组中元素可以组成目标值所有组合
注:
1.数组元素可以重复使用
2.所有数字(包括目标)都是正整数
3.解决方案集不得包含重复的组合
举例:
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]
]
解法一:
利用递归的思想,先将给定数组排序,这样在求和过程中,例如i处数字大于目标值,就不需要算i处往后的数值了,递归过程中将target值不断减去数组中的值,直到为0才添加到结果集合中
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(candidates);
Recursive(res,candidates,target,new ArrayList(),0);
return res;
}
public void Recursive(List<List<Integer>> res, int[] candidates, int target,
List<Integer> tempList,int index) {
if (target == 0) {
res.add(tempList);
return;
}
for (int i = index; i < candidates.length; i++) {
if (candidates[i] <= target) {
List<Integer> list = new ArrayList<>(tempList);
list.add(candidates[i]);
Recursive(res,candidates,target - candidates[i],list,i);
} else {
break;
}
}
}
}
小白刷题之路,请多指教— — 要么大器晚成,要么石沉大海