算法day20-回溯(2)
目录
- 组合总和
- 组合总和II
- 分割回文串 ⭐⭐⭐
一、组合总和
https://leetcode.cn/problems/combination-sum/description/?envType=problem-list-v2&envId=8At1GmaZ

class Solution { List<List<Integer>> res; List<Integer> path; public List<List<Integer>> combinationSum(int[] candidates, int target) { res = new ArrayList<>(); path = new ArrayList<>(); dfs(0, target, candidates, 0); return res; } public void dfs(int i, int target, int[] candidates,int sum){ if(sum == target){ //终止条件 res.add(new ArrayList<>(path)); return; } if(sum > target){ return; } for(int j=i; j<candidates.length; j++){ sum += candidates[j]; path.add(candidates[j]); dfs(j, target, candidates,sum); path.remove(path.size()-1); sum -= candidates[j]; } } }
二、组合总和II
https://leetcode.cn/problems/combination-sum-ii/?envType=problem-list-v2&envId=8At1GmaZ

class Solution { List<List<Integer>> res; List<Integer> path; int[] visited; public List<List<Integer>> combinationSum2(int[] candidates, int target) { res = new ArrayList<>(); path = new ArrayList<>(); visited = new int[candidates.length]; Arrays.sort(candidates); dfs(0, candidates, target, 0); return res; } public void dfs(int i, int[] candidates, int target, int sum){ if(sum == target){ res.add(new ArrayList<>(path)); return; } if(sum > target){ return; } for(int j=i; j<candidates.length; j++){ // 对于每一层,如果有重复的数字-->跳过选择 // 假如第一层选定了,第二层选过了x,那么这个第二层就不能再选x了 if(j > i && candidates[j] == candidates[j - 1]) continue; path.add(candidates[j]); dfs(j+1, candidates, target, sum + candidates[j]); path.remove(path.size()-1); } } }
三、分割回文串
https://leetcode.cn/problems/palindrome-partitioning/?envType=problem-list-v2&envId=8At1GmaZ

class Solution { List<List<String>> res; List<String> path; public List<List<String>> partition(String s) { res = new ArrayList<>(); path = new ArrayList<>(); dfs(0, s); return res; } public void dfs(int start, String s){ if(start == s.length()){ res.add(new ArrayList<>(path)); return; } for(int end = start; end<s.length();end++){ if (isPalindrome(s, start, end)) { path.add(s.substring(start, end+1)); dfs(end + 1, s); path.remove(path.size()-1); } } } public boolean isPalindrome(String s, int start, int end){ if(s == null){ return true; } while(start < end){ if(s.charAt(start) != s.charAt(end)){ return false; } start++; end--; } return true; } }
浙公网安备 33010602011771号