Leetcode解题笔记-Combination Sum
题目要求:
给出一个int数组以及一个target数字找出所有在此范围中找出所有组合可以得出target的结果
解题思路:
1.利用递归,每次根据index更新copy结果集
2.定义newtarget= target-candidates[i]
3 每更新一次newtarget相对于target就更近了一步
4.当target等于0的时候得出结果
相关代码:
public static List<List<Integer>> combinationSum(int[] candidates, int target){
List<List<Integer>> result = new ArrayList<List<Integer>>();
Arrays.sort(candidates);
resurce(new ArrayList<Integer>(), candidates, target, 0, result);
return result;
}
private static void resurce(List<Integer> list, int[] candidate, int target, int index, List<List<Integer>> result){
if(target==0){
result.add(list);
}
for (int i = 0; i < candidate.length; i++) {
if(target>=0){
int newtarget = target - candidate[i];
List<Integer> copy = new ArrayList<Integer>(list);
resurce(copy, candidate, newtarget, i, result);
}else {
break;
}
}