文章目录
- Leetcode 39. 组合总和
- 解题思路
- 代码
- 总结
- Leetcode 40. 组合总和 II
- 解题思路
- 代码
- 总结
- Leetcode 131. 分割回文串
- 解题思路
- 代码
- 总结
草稿图网站
java的Deque
Leetcode 39. 组合总和
题目:39. 组合总和
解析:代码随想录解析
解题思路
还是回溯三部曲
代码
class Solution {List<List<Integer>> res = new ArrayList<>();List<Integer> paths = new ArrayList<>();int curSum = 0;private void backtracking(int[] candidates, int target, int startIndex) {if (curSum >= target) {if (curSum == target)res.add(new ArrayList<>(paths));return;}for (int i = startIndex; i < candidates.length; i++) {paths.add(candidates[i]);curSum += candidates[i];backtracking(candidates, target, i);paths.remove(paths.size() -1);curSum -= candidates[i];}}public List<List<Integer>> combinationSum(int[] candidates, int target) {backtracking(candidates, target, 0);return res;}
}
总结
越来越熟练了
Leetcode 40. 组合总和 II
题目:40. 组合总和 II
解析:代码随想录解析
解题思路
递归加一定的减枝,如果第一个元素一样的话,就跳过。
代码
class Solution {List<List<Integer>> res = new ArrayList<>();List<Integer> paths = new ArrayList<>();int curSum = 0;private void backtracking(int[] candidates, int target, int startIndex) {if (curSum >= target) {if (curSum == target)res.add(new ArrayList<>(paths));return;}for (int i = startIndex; i < candidates.length; i++) {if (i > startIndex && candidates[i] == candidates[i-1])continue;paths.add(candidates[i]);curSum += candidates[i];backtracking(candidates, target, i + 1);paths.remove(paths.size() - 1);curSum -= candidates[i];}}public List<List<Integer>> combinationSum2(int[] candidates, int target) {Arrays.sort(candidates);backtracking(candidates, target, 0);return res;}
}
总结
暂无
Leetcode 131. 分割回文串
题目:131. 分割回文串
解析:代码随想录解析
解题思路
一个函数判断是否是回文
一个回溯函数
代码
class Solution {List<List<String>> res = new ArrayList<>();List<String> paths = new ArrayList<>();private boolean isPalindrome(String s, int begin, int end) {for (int i = begin, j = end; i < j; i++, j--) {if (s.charAt(i) != s.charAt(j))return false;}return true;}private void backtracking(String s, int startIndex){if (startIndex == s.length()) {res.add(new ArrayList<>(paths));return;}for (int i = startIndex; i < s.length(); i++) {if (isPalindrome(s, startIndex, i)) {paths.add(s.substring(startIndex, i+1));backtracking(s, i+1);paths.remove(paths.size()-1);}}}public List<List<String>> partition(String s) {backtracking(s, 0);return res;}
}
总结
暂无