【回溯】回溯问题的两个模板
模板一:
采用深度优先搜索
class Solution { List<Integer> temp = new ArrayList<Integer>(); List<List<Integer>> ans = new ArrayList<List<Integer>>(); public List<List<Integer>> combinationSum3(int k, int n) { dfs(1, 9, k, n); return ans; } public void dfs(int cur, int n, int k, int sum) { if (temp.size() + (n - cur + 1) < k || temp.size() > k) { return; } if (temp.size() == k) { int tempSum = 0; for (int num : temp) { tempSum += num; } if (tempSum == sum) { ans.add(new ArrayList<Integer>(temp)); return; } } temp.add(cur); dfs(cur + 1, n, k, sum); temp.remove(temp.size() - 1); dfs(cur + 1, n, k, sum); } }
模板二:
采用广度优先搜索
class Solution { List<List<Integer>> res = new ArrayList<>(); List<Integer> tmp = new ArrayList<>(); int curSum = 0; public List<List<Integer>> combinationSum3(int k, int n) { dfs(1,n,k); return res; } public void dfs(int cur,int n,int k){ if(tmp.size() == k && curSum == n){ res.add(new ArrayList<>(tmp)); } for(int i = cur;i<=9;i++){ tmp.add(i); curSum +=i; dfs(i+1,n,k); curSum -=i; tmp.remove(tmp.size()-1); } } }

浙公网安备 33010602011771号