题目
● 39. 组合总和
● 40.组合总和II
● 131.分割回文串
解答
这三个题目都与组合有关,下面我将简单介绍一下它们的思路和解法。
- 组合总和
这道题目是一个典型的回溯算法问题。我们可以先将数组排序,然后从小到大依次枚举每一个数,每次将当前数加入到已选集合中,然后递归搜索剩余的部分,直到满足条件或者不满足条件为止。如果满足条件,就将当前选中的集合加入到结果中。
Java代码如下:
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(candidates);
backtrack(candidates, target, res, new ArrayList<>(), 0);
return res;
}
private void backtrack(int[] candidates, int target, List<List<Integer>> res, List<Integer> temp, int start) {
if (target == 0) {
res.add(new ArrayList<>(temp));
return;
}
for (int i = start; i < candidates.length; i++) {
if (candidates[i] > target) {
break;
}
temp.add(candidates[i]);
backtrack(candidates, target - candidates[i], res, temp, i);
temp.remove(temp.size() - 1);
}
}
}
- 组合总和 II
这道题目和上一道题目类似,只不过每个数只能用一次,因此我们需要在递归回溯的时候,从当前位置的下一位开始搜索。另外,还需要去重,因为不能出现重复的组合。
Java代码如下:
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(candidates);
backtrack(candidates, target, res, new ArrayList<>(), 0);
return res;
}
private void backtrack(int[] candidates, int target, List<List<Integer>> res, List<Integer> temp, int start) {
if (target == 0) {
res.add(new ArrayList<>(temp));
return;
}
for (int i = start; i < candidates.length; i++) {
if (i > start && candidates[i] == candidates[i - 1]) {
continue;
}
if (candidates[i] > target) {
break;
}
temp.add(candidates[i]);
backtrack(candidates, target - candidates[i], res, temp, i + 1);
temp.remove(temp.size() - 1);
}
}
}
- 分割回文串
这道题目是一个比较经典的动态规划问题。我们可以使用一个二维数组dp[i][j]表示从i到j是否是回文串。定义dp[i][j]为true,当且仅当s[i]等于s[j],并且s[i+1]到s[j-1]是回文串。
有了这个状态定义之后,我们就可以使用dp解决问题了。具体来说,我们可以先预处理出dp数组,然后使用回溯算法枚举所有的可能分割方式,如果当前分割方式是合法的,则将其加入到结果中。
Java代码如下:
class Solution {
public List<List<String>> partition(String s) {
int n = s.length();
boolean[][] dp = new boolean[n][n];
for (int i = n - 1; i >= 0; i--) {
for (int j = i; j < n; j++) {
dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i <= 2 || dp[i + 1][j - 1]);
}
}
List<List<String>> res = new ArrayList<>();
backtrack(s, dp, res, new ArrayList<>(), 0);
return res;
}
private void backtrack(String s, boolean[][] dp, List<List<String>> res, List<String> temp, int start) {
if (start == s.length()) {
res.add(new ArrayList<>(temp));
return;
}
for (int i = start; i < s.length(); i++) {
if (dp[start][i]) {
temp.add(s.substring(start, i + 1));
backtrack(s, dp, res, temp, i + 1);
temp.remove(temp.size() - 1);
}
}
}
}