题目链接
法一(回溯)
public class Solution39 {
private List<List<Integer>> ans;
private List<Integer> path;
public Solution39() {
this.ans = new LinkedList<>();
this.path = new LinkedList<>();
}
void backTracking(int[] candidates, int target, int sum, int start) {
if (sum > target) {
return;
}
if (sum == target) {
ans.add(new LinkedList<>(path));
return;
}
for (int i = start; i < candidates.length; i++) {
sum += candidates[i];
path.add(candidates[i]);
backTracking(candidates, target, sum, i);
sum -= candidates[i];
path.remove(path.size() - 1);
}
}
public List<List<Integer>> combinationSum(int[] candidates, int target) {
backTracking(candidates, target, 0, 0);
return ans;
}
法二(回溯 + 剪枝)
public class Solution39 {
private List<List<Integer>> ans;
private List<Integer> path;
public Solution39() {
this.ans = new LinkedList<>();
this.path = new LinkedList<>();
}
void backTracking_2(int[] candidates, int target, int sum, int start) {
if (sum == target) {
ans.add(new LinkedList<>(path));
return;
}
for (int i = start; i < candidates.length && sum + candidates[i] <= target; i++) {
sum += candidates[i];
path.add(candidates[i]);
backTracking_2(candidates, target, sum, i);
sum -= candidates[i];
path.remove(path.size() - 1);
}
}
public List<List<Integer>> combinationSum_2(int[] candidates, int target) {
Arrays.sort(candidates);
backTracking_2(candidates, target, 0, 0);
return ans;
}
本地测试
lay.showTitle(39);
int[] candidates39 = new int[]{2,3,5};
int target39 = 8;
Solution39 sol39_1 = new Solution39();
List<List<Integer>> ans39_1 = sol39_1.combinationSum(candidates39, target39);
arrayOpt.showIntLists(ans39_1);
System.out.println();
Solution39 sol39_2 = new Solution39();
List<List<Integer>> ans39_2 = sol39_2.combinationSum_2(candidates39, target39);
arrayOpt.showIntLists(ans39_2);