一、39.组合总和
本题整数数组中无重复元素,不需要去重操作,较为简单。
代码如下:
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backTracking(vector<int>& candidates, int target, int sum, int startIndex) {
if (sum == target) {
result.push_back(path);
return;
}
for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++) {
sum += candidates[i];
path.push_back(candidates[i]);
backTracking(candidates, target, sum, i);
sum -= candidates[i];
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
backTracking(candidates, target, 0, 0);
return result;
}
};
二、40.组合总和II(复习)
本题的整数数组candidates有重复元素,需要去重。
去重的操作主要体现在for循环中:
if (i > 0 && candidates[i] == candidates[i-1] && used[i-1] == false) {
continue;
如何理解呢?
首先增加一个bool类型的数组used,用来记录同一树枝上的元素是否使用过。(去重就是用used去重)
(以下以candidates=[1,1,2]为例)
还没完全明白,明天看懂了再补充。
代码如下:
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backTracking(vector<int>& candidates, int target, int sum, int startIndex, vector<bool>& used) {
if (sum > target) return;
if (sum == target) {
result.push_back(path);
return;
}
for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++) {
if (i > 0 && candidates[i] == candidates[i-1] && used[i-1] == false) {
continue;
}
sum += candidates[i];
path.push_back(candidates[i]);
used[i] = true;
backTracking(candidates, target, sum, i + 1, used);
sum -= candidates[i];
path.pop_back();
used[i] = false;
}
}
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<bool> used(candidates.size(), false);
sort(candidates.begin(), candidates.end());
backTracking(candidates, target, 0, 0, used);
return result;
}
};
三、131.分割回文串
代码如下:
class Solution {
private:
bool isPalindrome(const string& s, int start, int end) { // 该函数一定要写在回溯前面,不然会显示未定义isPalindrome错误
for (int i = start, j = end; i < j; i++, j--) {
if (s[i] != s[j]) {
return false;
}
}
return true;
}
vector<vector<string>> result;
vector<string> path;
void backtracking(const string& s, int startIndex) {
if (startIndex >= s.size()) {
result.push_back(path);
return;
}
for (int i = startIndex; i < s.size(); i++) {
if (isPalindrome(s, startIndex, i)) {
string str = s.substr(startIndex, i - startIndex + 1); // 获取[startIndex,i]在string中的子串
path.push_back(str);
}
else continue;
backtracking(s, i + 1);
path.pop_back();
}
}
public:
vector<vector<string>> partition(string s) {
backtracking(s, 0);
return result;
}
};