纠正39.组合总和 Java版本代码

This commit is contained in:
hk27xing
2021-05-29 16:13:32 +08:00
parent 1f350021e3
commit fb91b760eb

View File

@ -237,34 +237,28 @@ public:
Java Java
```Java ```Java
// 剪枝优化
class Solution { class Solution {
List<List<Integer>> lists = new ArrayList<>(); public List<List<Integer>> combinationSum(int[] candidates, int target) {
Deque<Integer> deque = new LinkedList<>(); List<List<Integer>> res = new ArrayList<>();
Arrays.sort(candidates); // 先进行排序
public List<List<Integer>> combinationSum3(int k, int n) { backtracking(res, new ArrayList<>(), candidates, target, 0, 0);
int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}; return res;
backTracking(arr, n, k, 0);
return lists;
} }
public void backTracking(int[] arr, int n, int k, int startIndex) { public void backtracking(List<List<Integer>> res, List<Integer> path, int[] candidates, int target, int sum, int idx) {
//如果 n 小于0没必要继续本次递归已经不符合要求了 // 找到了数字和为 target 的组合
if (n < 0) { if (sum == target) {
res.add(new ArrayList<>(path));
return; return;
} }
if (deque.size() == k) {
if (n == 0) { for (int i = idx; i < candidates.length; i++) {
lists.add(new ArrayList(deque)); // 如果 sum + candidates[i] > target 就终止遍历
} if (sum + candidates[i] > target) break;
return; path.add(candidates[i]);
} backtracking(res, path, candidates, target, sum + candidates[i], i);
for (int i = startIndex; i < arr.length - (k - deque.size()) + 1; i++) { path.remove(path.size() - 1); // 回溯,移除路径 path 最后一个元素
deque.push(arr[i]);
//减去当前元素
n -= arr[i];
backTracking(arr, n, k, i + 1);
//恢复n
n += deque.pop();
} }
} }
} }