目录
1. T39:组合总和
T39:给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。
提示:
-
1 <= candidates.length <= 30
-
2 <= candidates[i] <= 40
-
candidates 的所有元素 互不相同
-
1 <= target <= 40
S:本题跟先前唯一的不同之处在于同一个数字可以重复选取,别的基本一致
本题Carl还提出了一个总结点:
⭐何时需要startIndex
- 如果是一个集合来求组合的话,就需要startIndex
- 如果是多个集合取组合,各个集合之间相互不影响,那么就不用startIndex
显然本题符合第一种情况
C++:用递减式写,可以少传一个参数int sum
而且如下所见,剪枝优化的写法有2种(C++版中采用第1种):
- 在for循环中的逻辑里设置 if (target - candidates[i] >= 0);
- 在for循环的循环进行条件中加上,但这么写需要提前进行升序排序
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
if (candidates.size() == 0) return res;
// sort(candidates.begin(), candidates.end()); // 1、either需要排序
backTracking(candidates, target, 0);
return res;
}
private:
vector<vector<int>> res;
vector<int> path;
void backTracking(vector<int>& candidates, int target, int startIndex) {
if (target == 0) {
res.push_back(path);
return;
}
if (target < 0) return;
//1、either
// for (int i = startIndex; i < candidates.size() && target - candidates[i] >= 0; ++i) {
for (int i = startIndex; i < candidates.size(); ++i) {//2、or
path.push_back(candidates[i]);//放下面的if里外都可以
if (target - candidates[i] >= 0) {//2、or:这样写就不用先排好序
backTracking(candidates, target - candidates[i], i);// 关键点:不用i+1了,表示可以重复读取当前的数
}
path.pop_back();
}
}
Java:Java版用递增式写,剪枝优化采用第2种
List<List<Integer>> res;
LinkedList<Integer> path;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
res = new ArrayList<>();
if (candidates.length == 0) return res;
Arrays.sort(candidates);//
path = new LinkedList<>();
backTracking(candidates, target, 0, 0);
return res;
}
private void backTracking(int[] candidates, int target, int sum, int startIndex) {
if (sum == target) {
res.add(new LinkedList<>(path));
return;
}
if (sum > target) return;
// for (int i = startIndex; i < candidates.length; ++i) {
//下一行为剪枝,注意:如果要这么写,必须先确保candidates是升序的
for (int i = startIndex; i < candidates.length && sum + candidates[i] <= target; ++i) {
path.add(candidates[i]);
//或者不排序、不在for循环中设置条件,在这里设个if
backTracking(candidates, target, sum + candidates[i], i);
path.removeLast();
}
}
2. T40:组合总和Ⅱ
T27:给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用 一次 。
注意:解集不能包含重复的组合。
提示:
-
1 <= candidates.length <= 100
-
1 <= candidates[i] <= 50
-
1 <= target <= 30
S:本题可谓是组合总和的集大成者~
注意:题目中说不能包含重复的组合,每个数字在每个组合中只用使用一次,但并不意味着集合中每个数的值都是不同的!
翻译成N叉树去重思路的话,就是:
- 对同层,也就是不同组合(树枝)之间,遇到同值的数字就跳过;
- 对同枝,也就是同一组合内部,可以允许使用同值的数字,但并不是原数组中同一索引位置上的同一个数字!
C++:
版本Ⅰ、
在该版本中,专门设置了一个与所给数组等长的数组,用于标记、区分对应索引位置的数字是否被上一组合(树枝),还是被本组合内上一层的递归使用着,当排序后的数组出现了相邻值相等,可分为以下两种情况:
- candidates[i] == candidates[i - 1] 且 used[i - 1] == false,就说明:前一个树枝,使用了candidates[i - 1],也就是说同一树层使用过candidates[i - 1],需要进行去重;
- candidates[i] == candidates[i - 1] 且 used[i - 1] == true,就说明:本树枝的前一个位置,使用了candidates[i - 1],不需要进行去重。
代码实现如下:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
if (candidates.size() == 0) return res;
vector<bool> used(candidates.size(), false);
sort(candidates.begin(), candidates.end());
backTracking(candidates, target, 0, used);
return res;
}
private:
vector<vector<int>> res;
vector<int> path;
void backTracking(vector<int>& candidates, int target, int startIndex, vector<bool>& used) {
if (target == 0) {
res.push_back(path);
return;
}
// if (target < 0) return;
for (int i = startIndex; i < candidates.size(); ++i) {
if (i > 0 && candidates[i] == candidates[i - 1] && used[i - 1] == false) {
continue;
}
path.push_back(candidates[i]);
if (target - candidates[i] >= 0) {
// path.push_back(candidates[i]);//里外皆可
used[i] = true;
// backTracking(candidates, target - candidates[i], i, used);
// 和39.组合总和的区别1,这里是i+1,每个数字(🚩同值数字不一定只有1个)在每个组合中只能使用一次
backTracking(candidates, target - candidates[i], i + 1, used);
used[i] = false;
// path.pop_back();
}
path.pop_back();
}
}
版本Ⅱ、
其实也可以不需要设置专门的标记数组,如下:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
if (candidates.size() == 0) return res;
sort(candidates.begin(), candidates.end());
backTrackint(candidates, target, 0);
return res;
}
private:
vector<vector<int>> res;
vector<int> path;
void backTrackint(vector<int>& candidates, int remain, int startIndex) {
if (remain == 0) {
res.push_back(path);
return;
}
for (int i = startIndex; i < candidates.size() && remain - candidates[i] >= 0; ++i) {
// 要对同一树层使用过的元素进行跳过
if (i > startIndex && candidates[i] == candidates[i - 1]) {
continue;
}
path.push_back(candidates[i]);
backTrackint(candidates, remain - candidates[i], i + 1);
path.pop_back();
}
}
Java:
版本Ⅰ、
List<List<Integer>> res;
LinkedList<Integer> path;
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
res = new ArrayList<>();
if (candidates.length == 0) return res;
Arrays.sort(candidates);
path = new LinkedList<>();
backTracking(candidates, target, 0, new boolean[candidates.length]);
return res;
}
private void backTracking(int[] candidates, int remain, int startIndex, boolean[] used) {
if (remain == 0) {
res.add(new LinkedList<>(path));
return;
}
for (int i = startIndex; i < candidates.length && remain - candidates[i] >= 0; ++i) {
if (i > 0 && candidates[i] == candidates[i - 1] && used[i - 1] == false) {
continue;
}
path.add(candidates[i]);
used[i] = true;
backTracking(candidates, remain - candidates[i], i + 1, used);
used[i] = false;
path.removeLast();
}
}
版本Ⅱ、
List<List<Integer>> res;
LinkedList<Integer> path;
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
res = new ArrayList<>();
if (candidates.length == 0) return res;
Arrays.sort(candidates);
path = new LinkedList<>();
backTracking(candidates, target, 0);
return res;
}
private void backTracking(int[] candidates, int remain, int startIndex) {
if (remain == 0) {
res.add(new LinkedList<>(path));
return;
}
for (int i = startIndex; i < candidates.length && remain - candidates[i] >= 0; ++i) {
if (i > startIndex && candidates[i] == candidates[i - 1]) {
continue;
}
path.add(candidates[i]);
backTracking(candidates, remain - candidates[i], i + 1);
path.removeLast();
}
}
3. T131:分割回文串
T131:给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串。
提示:
-
1 <= s.length <= 16
-
s 仅由小写英文字母组成
S:
本题的要点主要就俩:
- 如何判断字符串是否为回文串
- 初步:直接用双指针法,从字符串的首尾字符一一比较并同步收缩,直到双指针并拢
- 如何切割出字符串的所有子串
- 递归回溯~
C++:
vector<vector<string>> partition(string s) {
if (s.size() == 0) return res;
backTracking(s, 0);
return res;
}
private:
vector<vector<string>> res;
vector<string> path;// 放已经回文的子串
void backTracking(string& s, int startIndex) {
// 如果起始位置已经大于s的大小,说明已经找到了一组分割方案了
if (startIndex >= s.size()) {
res.push_back(path);
return;
}
for (int i = startIndex; i < s.size(); ++i) {
if (isPalindrome(s, startIndex, i)) {
// 获取[startIndex,i]在s中的子串
// string str = s.substr(startIndex, i);//第二个参数是跨度(左闭右闭)
string str = s.substr(startIndex, i - startIndex + 1);
path.push_back(str);
} else {
continue;
}
backTracking(s, i + 1);
path.pop_back();// 回溯过程,弹出本次已经填入的子串(此时所有的回文串都已经加入了结果中)
}
}
bool isPalindrome(const string& s, int start, int end) {
for (; start < end; ++start, --end) {
if (s[start] != s[end]) return false;
}
return true;
}
Java:
List<List<String>> res;
LinkedList<String> path;
public List<List<String>> partition(String s) {
res = new ArrayList<>();
if (s == null || s.length() == 0 || s.equals("")) return res;
path = new LinkedList<>();
backTracking(s, 0);
return res;
}
private void backTracking(String s, int startIndex) {
if (startIndex >= s.length()) {
res.add(new LinkedList<>(path));
return;
}
for (int i = startIndex; i < s.length(); ++i) {
if (judge(s, startIndex, i) == true) {
String str = s.substring(startIndex, i + 1);//不同于C++,第二个参数是endIndex,左开右闭
path.add(str);
} else {
continue;
}
backTracking(s, i + 1);
path.removeLast();
}
}
private boolean judge(String s, int start, int end) {
while (start < end) {
if (s.charAt(start) != s.charAt(end)) {
return false;
}
++start;
--end;
}
return true;
}
优化【涉及动态规划】
优化思路就是不需要每次所有子串都调用定义的双指针遍历方法检查该子串是否为回文串,而是一上来就检查原始的字符串,同时用一个数组保存不断截取的字串是否为回文串的结果。
其实我个人还没完全理解(就欠🚩标记的一行。。。)
C++:
vector<vector<string>> partition(string s) {
if (s.size() == 0) return res;
computeIsPalindrome(s);
backTracking(s, 0);
return res;
}
private:
vector<vector<string>> res;
vector<string> path;
vector<vector<bool>> isPalindrome;
void backTracking(const string&s, int startIndex) {
if (startIndex >= s.size()) {
res.push_back(path);
return;
}
for (int i = startIndex; i < s.size(); ++i) {
if (isPalindrome[startIndex][i]) {
string str = s.substr(startIndex, i - startIndex + 1);
path.push_back(str);
} else {
continue;
}
backTracking(s, i + 1);
path.pop_back();
}
}
void computeIsPalindrome(const string& s) {
// 根据字符串s, 刷新布尔矩阵的大小
isPalindrome.resize(s.size(), vector<bool>(s.size(), false));
for (int i = s.size() - 1; i >= 0; --i) {
for (int j = i; j < s.size(); ++j) {
if (i == j) isPalindrome[i][j] = true;
else if (j - i == 1) isPalindrome[i][j] = s[i] == s[j];
else {
//🚩灵魂行
isPalindrome[i][j] = (s[i] == s[j] && isPalindrome[i + 1][j - 1]);
}
}
}
}
Java:
List<List<String>> res;
LinkedList<String> path;
boolean[][] isPalindrome;
public List<List<String>> partition(String s) {
res = new ArrayList<>();
if (s == null || s.length() == 0 || s.equals("")) return res;
// isPalindrome = new boolean[s.length()];
computeIsPalindrome(s);
path = new LinkedList<>();
backTracking(s, 0);
return res;
}
private void backTracking(String s, int startIndex) {
if (startIndex >= s.length()) {
res.add(new LinkedList<>(path));
return;
}
for (int i = startIndex; i < s.length(); ++i) {
if (isPalindrome[startIndex][i] == true) {
String str = s.substring(startIndex, i + 1);
path.add(str);
} else {
continue;
}
backTracking(s, i + 1);
path.removeLast();
}
}
private void computeIsPalindrome(String s) {
// isPalindrome = new boolean[s.length()];
//🚩上面那行:error: boolean[] cannot be converted to boolean[][]
isPalindrome = new boolean[s.length()][s.length()];
for (int i = s.length() - 1; i >= 0; --i) {
for (int j = i; j < s.length(); ++j) {
if (j == i) isPalindrome[i][j] = true;
else if (j - i == 1) isPalindrome[i][j] = s.charAt(i) == s.charAt(j);
else {
// isPalindrome[i][j] = s.charAt(i) == s.charAt(j) && s.charAt(i + 1) == s.charAt(j - 1);
isPalindrome[i][j] = s.charAt(i) == s.charAt(j) && isPalindrome[i + 1][j - 1] == true;
}
}
}
}