LeetCode216.組合總數III
阿新 • • 發佈:2022-05-16
程式碼1(自己)
class Solution { List<List<Integer>> res = new ArrayList<>(); List<Integer> path = new ArrayList<>(); public List<List<Integer>> combinationSum3(int k, int n) { backtracking(k, n, 1); return res; } public void backtracking(int k, int n, int startIndex) { if (path.size() == k) { if (getSum(path) == n) { res.add(new ArrayList<>(path)); //return; } return; } for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i ++) { path.add(i); backtracking(k, n, i + 1); path.remove(path.size() - 1); } } public int getSum(List<Integer> path) { int sum = 0; for (int i = 0; i < path.size(); i ++) { sum += path.get(i); } return sum; } }
剪枝操作: for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i ++) {}
程式碼2(程式碼隨想錄)
class Solution { List<List<Integer>> res = new ArrayList<>(); List<Integer> path = new ArrayList<>(); public List<List<Integer>> combinationSum3(int k, int n) { backtracking(k, n, 0, 1); return res; } public void backtracking(int k, int n, int sum, int startIndex) { if (path.size() == k) { if (sum == n) { res.add(new ArrayList<>(path)); } return; } for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i ++) { sum += i; // 處理 path.add(i); // 處理 backtracking(k, n, sum, i + 1); // 回溯 sum -= i; // 撤銷 path.remove(path.size() - 1); // 撤銷 } } }
注意:
恢復現場
處理過程和回溯過程是一一對應的,處理過程中有加法操作,回溯過程就要有對應的減法操作。