使用递归算法,将数组排序方便剪枝
1.正序
/**
* 正序,注意题目条件,没有重复数字
*/
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
//排序成有序数组方便剪枝
Arrays.sort(candidates);
List<List<Integer>> ans = new ArrayList<>();
List<Integer> combine = new ArrayList<>();
dfs(ans,combine,candidates,0,target,0);
return ans;
}
public void dfs(List<List<Integer>> ans, List<Integer> combine, int[] candidates,
int sum, int target, int idx){
//递归终止条件
if(sum == target){
ans.add(new ArrayList<Integer>(combine));
return;
}
for (int i = idx; i < candidates.length; i++) {
int _sum = sum + candidates[i];
if(_sum <= target){
combine.add(candidates[i]);
dfs(ans,combine,candidates,_sum,target,i);
combine.remove(combine.size() - 1);
} else {
//顺序数组可以使用break
break;
}
}
}
public static void main(String[] args) {
Solution solution = new Solution();
List<List<Integer>> lists = solution.combinationSum(new int[]{2, 3, 6, 7}, 7);
for (List<Integer> list : lists) {
System.out.println(list);
}
}
}
2.逆序
/**
* 逆序
*/
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> combine = new ArrayList<>();
dfs(ans,combine,target,0,candidates);
return ans;
}
/**
*
* @param ans 所有答案
* @param combine 当前答案
* @param target 剩余的数
* @param idx 当前的遍历到的索引
* @param candidates 候选数组
*/
public void dfs(List<List<Integer>> ans,List<Integer> combine,int target,int idx,int[] candidates){
//结束条件
if(idx == candidates.length){
return;
}
if(target == 0){
//必须定义新ArrayList存储
ans.add(new ArrayList<>(combine));
return;
}
//跳过当前的数字(从后往前枚举)
dfs(ans,combine,target,idx + 1,candidates);
//试探当前的数字是否符合要求
if(target - candidates[idx] >= 0){
combine.add(candidates[idx]);
dfs(ans,combine,target - candidates[idx],idx,candidates);
//回溯回来,移除试探添加的数字
combine.remove(combine.size() - 1);
}
}
public static void main(String[] args) {
Solution solution = new Solution();
List<List<Integer>> lists = solution.combinationSum(new int[]{2, 3, 6, 7}, 7);
for (List<Integer> list : lists) {
System.out.println(list);
}
}
}