文章目录
39. 组合总和
给你一个 无重复元素 的整数数组 candidates
和一个目标整数 target
,找出 candidates
中可以使数字和为目标数 target
的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates
中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target
的不同组合数少于 150
个。
示例 1:
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。
示例 2:
输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]
示例 3:
输入: candidates = [2], target = 1
输出: []
思路
本题没有数量要求,可以无限重复,但是有总和的限制,所以间接的也是有个数的限制。
每次都可以从一个新的candidate数组里取数字
难点:startIndex
不是可以重复取吗,这里还要一个startIndex,每次for都从i=0
开始而不是从i=startIndex
开始不行吗?
一开始我也在这里中招了,因为这是个组合问题而不是排列问题,如果从第二个元素开始还对第一个元素判断是否满足要求,则会造成重复的问题
比如candidate = [2, 3, 8],target = 5,每层循环都从i=0开始
- 从2开始取:第一层i=0循环取到2,第二层i=1取到3,最终得到组合[2, 3]
- 从3开始取:第一层i=1循环得到3,第二层i=0得到2,最终得到组合[3, 2]
这虽然是不同的排列,但造成了重复的组合
所以一定要设定startIndex,下一层也从当前的元素开始取
回溯三部曲
- 递归函数参数
定义两个全局变量,二维数组result存放结果集,数组path存放符合条件的结果。
首先是题目中给出的参数,集合candidates, 和目标值target。然后每个path里的和为sum,startIndex用来指定当前开始选择元素的位置
LinkedList<Integer> path = new LinkedList<>();
List<List<Integer>> res = new ArrayList<>();
void backtracking(int[] candidates, int target, int sum, int startIndex) {
- 递归终止条件
终止只有两种情况,sum大于target和sum等于target。其中sum等于target的时候,需要收集结果。
if (sum > targrt) {
return;
}
if (sum == targrt) {
res.add(new ArrayList<>(path));
return;
}
- 单层搜索的逻辑
单层for循环依然是从startIndex开始,搜索candidates集合。从当前的i开始(包括i)可以重复选取
// 单层选数
for (int i = startIndex; i < candidates.length; i++) {
sum += candidates[i];
path.add(candidates[i]);
backtracking(candidates, target, sum, i);
sum -= candidates[i];
path.removeLast(); // 回溯
}
完整代码:
public List<List<Integer>> combinationSum(int[] candidates, int target) {
backtracking(candidates, target, 0, 0);
return res;
}
LinkedList<Integer> path = new LinkedList<>();
List<List<Integer>> res = new ArrayList<>();
void backtracking(int[] candidates, int target, int sum, int startIndex) {
if (sum > target) {
return;
}
if (sum == target) {
res.add(new ArrayList<>(path));
return;
}
// 单层选数
for (int i = startIndex; i < candidates.length; i++) {
sum += candidates[i];
path.add(candidates[i]);
backtracking(candidates, target, sum, i);
sum -= candidates[i];
path.removeLast(); // 回溯
}
}
剪枝优化
对于sum已经大于target的情况,其实是依然进入了下一层递归,只是下一层递归结束判断的时候,会判断sum > target的话就返回。
其实如果已经知道下一层的sum会大于target,就没有必要进入下一层递归了。
那么就可以在for循环里添加判断条件
对总集合排序之后,如果下一层的sum(就是本层的 sum + candidates[i])已经大于target,就可以结束本轮for循环的遍历。
完整代码:
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates); // 先进行排序
backtracking(candidates, target, 0, 0);
return res;
}
LinkedList<Integer> path = new LinkedList<>();
List<List<Integer>> res = new ArrayList<>();
void backtracking(int[] candidates, int target, int sum, int startIndex) {
if (sum == target) {
res.add(new ArrayList<>(path));
return;
}
// 单层选数
for (int i = startIndex; i < candidates.length; i++) {
if (sum + candidates[i] > target) break;
sum += candidates[i];
path.add(candidates[i]);
backtracking(candidates, target, sum, i);
sum -= candidates[i];
path.removeLast(); // 回溯
}
}
注:在求和问题中,排序之后加剪枝是常见的套路!
40. 组合总和II
给定一个候选人编号的集合 candidates
和一个目标数 target
,找出 candidates
中所有可以使数字和为 target
的组合。
candidates
中的每个数字在每个组合中只能使用 一次 。
**注意:**解集不能包含重复的组合。
示例 1:
输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/combination-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
示例 2:
输入: candidates = [2,5,2,1,2], target = 5,
输出:
[
[1,2,2],
[5]
]
思路
道题目关键在于和39题有如下区别:
- 本题candidates 中的每个数字在每个组合中只能使用一次。
- 本题数组candidates的元素是有重复的,而 39.组合总和 是无重复元素的数组candidates
都知道组合问题可以抽象为树形结构,那么“使用过”在这个树形结构上是有两个维度的,一个维度是同一树枝上使用过,一个维度是同一树层上使用过。
这道题目就是多了一步去重的步骤,其他的和39题无异。
难点:去重
回看一下题目所给的示例:
输入: candidates = [10,1,2,7,6,1,5], target = 8, 所求解集为: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]
元素在同一个组合内是可以重复的,怎么重复都没事,但两个组合不能相同。
所以我们要去重的是同一树层上的“使用过”,同一树枝上的都是一个组合里的元素,不用去重。
注:树层去重的话,需要对数组排序!
回溯三部曲:使用标记数组
- 递归函数参数
与39.组合总和 (opens new window)套路相同,此题还需要加一个bool型数组used,用来记录同一树枝上的元素是否使用过。
这个集合去重的重任就是used来完成的。
LinkedList<Integer> path = new LinkedList<>();
List<List<Integer>> res = new ArrayList<>();
void backtracking1(int[] candidates, int target, int sum, int startIndex, boolean[] used) {
- 递归终止条件
if (sum == target) {
res.add(new ArrayList<>(path));
}
- 单层搜索的逻辑
要去重的是“同一树层上的使用过”,如果判断同一树层上元素(相同的元素)是否使用过了呢。
如果candidates[i] == candidates[i - 1]
并且 used[i - 1] == false
,就说明:前一个树枝,使用了candidates[i - 1],也就是说同一树层使用过candidates[i - 1]。
此时for循环里就应该做continue的操作。
在candidates[i] == candidates[i - 1]相同的情况下:
- used[i - 1] == true,说明同一树枝candidates[i - 1]使用过
- used[i - 1] == false,说明同一树层candidates[i - 1]使用过
举例说明如下图:
通俗的解释就是,当我们当前元素和前一个元素相同时,前一个元素在上一层用过,used就会为true,当前还可以继续用。如果used为false说明之前的那条树枝(非上一层树枝)已经用过前一个相同的元素了,最后回溯回来为了看有无分支,重新置为了false,而当前元素和前一个一模一样,所以没必要在当前元素再往下试一次了,直接跳过!
// 单层
for (int i = startIndex; i < candidates.length; i++) {
if (sum + candidates[i] > target) break; // 剪枝不进入递归
// 去重
if (i > 0 && candidates[i] == candidates[i - 1] && used[i - 1] == false) {
continue;
}
sum += candidates[i];
path.add(candidates[i]);
used[i] = true;
backtracking1(candidates, target, sum, i + 1, used); // startIndex 每个数字在每个组合中只能使用一次
used[i] = false;
sum -= candidates[i];
path.removeLast();
}
完整代码:
// 使用标记数组
LinkedList<Integer> path = new LinkedList<>();
List<List<Integer>> res = new ArrayList<>();
void backtracking1(int[] candidates, int target, int sum, int startIndex, boolean[] used) {
if (sum == target) {
res.add(new ArrayList<>(path));
}
// 单层
for (int i = startIndex; i < candidates.length; i++) {
if (sum + candidates[i] > target) break; // 剪枝不进入递归
// 去重
if (i > 0 && candidates[i] == candidates[i - 1] && used[i - 1] == false) {
continue;
}
sum += candidates[i];
path.add(candidates[i]);
used[i] = true;
backtracking1(candidates, target, sum, i + 1, used); // startIndex 每个数字在每个组合中只能使用一次
used[i] = false;
sum -= candidates[i];
path.removeLast();
}
}
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
boolean[] used = new boolean[candidates.length];
// 加标志数组,用来辅助判断同层节点是否已经遍历
Arrays.fill(used, false);
Arrays.sort(candidates);
// 首先把给candidates排序,让其相同的元素都挨在一起。
backtracking1(candidates, target, 0, 0, used);
return res;
}
回溯三部曲:不使用标记数组
startIndex来去重也是可以的, 就不用used数组了。更容易理解
完整代码:
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
// 首先把给candidates排序,让其相同的元素都挨在一起。
backtracking(candidates, target, 0, 0);
return res;
}
LinkedList<Integer> path = new LinkedList<>();
List<List<Integer>> res = new ArrayList<>();
void backtracking(int[] candidates, int target, int sum, int startIndex) {
if (sum == target) {
res.add(new ArrayList<>(path));
}
// 单层
for (int i = startIndex; i < candidates.length; i++) {
if (sum + candidates[i] > target) break; // 剪枝不进入递归
// 去重
if (i > startIndex && candidates[i] == candidates[i - 1]) continue;
sum += candidates[i];
path.add(candidates[i]);
backtracking(candidates, target, sum, i + 1); // startIndex 每个数字在每个组合中只能使用一次
sum -= candidates[i];
path.removeLast();
}
}
131. 分割回文串
给你一个字符串 s
,请你将 s
分割成一些子串,使每个子串都是 回文串 。返回 s
所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串。
示例 1:
输入:s = "aab"
输出:[["a","a","b"],["aa","b"]]
示例 2:
输入:s = "a"
输出:[["a"]]
思路
切割问题类似组合问题
例如对于字符串abcdef:
- 组合问题:选取一个a之后,在bcdef中再去选取第二个,选取b之后在cdef中在选组第三个…。
- 切割问题:切割一个a之后,在bcdef中再去切割第二段,切割b之后在cdef中在切割第三段…。
难点:切割
如何切割呢?我一开始的想法是,先切割距离为一个字符,然后切割距离为两个字符,然后切割距离为三个字符,此时切到最后字符可能不够,这种方法但忽视了先切两个字符再切一个字符的情况,并不是每次切割的距离都是一样的。
那么在代码里什么是切割线呢?
实际上我们用startIndex切割,每一层的切割距离都是从一个字符开始,两个字符,三个字符不断增加,直到切到字符串末尾
如图所示
回溯三部曲
- 递归函数参数
全局变量数组path存放切割后回文的子串,二维数组result存放结果集。
本题递归函数参数还需要startIndex,因为切割过的地方,不能重复切割,和组合问题也是保持一致的。
LinkedList<String> path = new LinkedList<>();
List<List<String>> res = new ArrayList<>();
void backtracking(String s, int startIndex) {
- 递归函数终止条件
切割线切到了字符串最后面,说明找到了一种切割方法,此时就是本层递归的终止终止条件。
// 切到字符串末尾了
if (startIndex == s.length()) {
res.add(new ArrayList<>(path));
return;
}
- 单层搜索的逻辑
在for (int i = startIndex; i < s.size(); i++)
循环中,我们 定义了起始位置startIndex,那么 [startIndex, i] 就是要截取的子串。
首先判断这个子串是不是回文,如果是回文,就加入在path
中,path用来记录切割过的回文子串。
// 单层
for (int i = startIndex; i < s.length(); i++) {
// 字串
String str = s.substring(startIndex, i + 1); // 左闭右开
if (isPalindrome(str)) {
path.add(str);
}else continue; // 不是回文,跳到下一个字符
backtracking(s, i + 1);
path.removeLast(); // 回溯
}
注:切割过的位置,不能重复切割,所以,backtracking(s, i + 1); 传入下一层的起始位置为i + 1。
- 判断回文子串
双指针法
// 判断是否为回文字符串
boolean isPalindrome(String s) {
int left = 0;
int right= s.length() - 1;
while (left < right) {
if (s.charAt(left) == s.charAt(right)) {
left++;
right--;
}else return false;
}
return true;
}
完整代码:
public List<List<String>> partition(String s) {
backtracking(s, 0);
return res;
}
LinkedList<String> path = new LinkedList<>();
List<List<String>> res = new ArrayList<>();
void backtracking(String s, int startIndex) {
// 切到字符串末尾了
if (startIndex == s.length()) {
res.add(new ArrayList<>(path));
return;
}
// 单层
for (int i = startIndex; i < s.length(); i++) {
// 字串
String str = s.substring(startIndex, i + 1); // 左闭右开
if (isPalindrome(str)) {
path.add(str);
}else continue; // 不是回文,跳到下一个字符
backtracking(s, i + 1);
path.removeLast(); //回溯
}
}
// 判断是否为回文字符串
boolean isPalindrome(String s) {
int left = 0;
int right= s.length() - 1;
while (left < right) {
if (s.charAt(left) == s.charAt(right)) {
left++;
right--;
}else return false;
}
return true;
}