Skip to content

Commit

Permalink
Merge pull request youngyangyang04#290 from hk27xing/hk27xing-add
Browse files Browse the repository at this point in the history
纠正39.组合总和 Java版本代码
  • Loading branch information
youngyangyang04 authored May 30, 2021
2 parents 12795b9 + fb91b76 commit db0bcce
Showing 1 changed file with 17 additions and 23 deletions.
40 changes: 17 additions & 23 deletions problems/0039.组合总和.md
Original file line number Diff line number Diff line change
Expand Up @@ -237,34 +237,28 @@ public:

Java:
```Java
// 剪枝优化
class Solution {
List<List<Integer>> lists = new ArrayList<>();
Deque<Integer> deque = new LinkedList<>();

public List<List<Integer>> combinationSum3(int k, int n) {
int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
backTracking(arr, n, k, 0);
return lists;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(candidates); // 先进行排序
backtracking(res, new ArrayList<>(), candidates, target, 0, 0);
return res;
}

public void backTracking(int[] arr, int n, int k, int startIndex) {
//如果 n 小于0,没必要继续本次递归,已经不符合要求了
if (n < 0) {
return;
}
if (deque.size() == k) {
if (n == 0) {
lists.add(new ArrayList(deque));
}
public void backtracking(List<List<Integer>> res, List<Integer> path, int[] candidates, int target, int sum, int idx) {
// 找到了数字和为 target 的组合
if (sum == target) {
res.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i < arr.length - (k - deque.size()) + 1; i++) {
deque.push(arr[i]);
//减去当前元素
n -= arr[i];
backTracking(arr, n, k, i + 1);
//恢复n
n += deque.pop();

for (int i = idx; i < candidates.length; i++) {
// 如果 sum + candidates[i] > target 就终止遍历
if (sum + candidates[i] > target) break;
path.add(candidates[i]);
backtracking(res, path, candidates, target, sum + candidates[i], i);
path.remove(path.size() - 1); // 回溯,移除路径 path 最后一个元素
}
}
}
Expand Down

0 comments on commit db0bcce

Please sign in to comment.