mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
纠正39.组合总和 Java版本代码
This commit is contained in:
@ -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) {
|
||||
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;
|
||||
}
|
||||
if (deque.size() == k) {
|
||||
if (n == 0) {
|
||||
lists.add(new ArrayList(deque));
|
||||
}
|
||||
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 最后一个元素
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user