39.组合总和
题解
vector<int> path;
vector<vector<int>> result;
void back_tracking (vector<int>& candidates, int target, int sum, int startIndex) {
if (sum > target) {
return;
}
if (sum == target) {
result.push_back(path);
return;
}
for (int i = startIndex; i < candidates.size(); i++) {
sum += candidates[i];
path.push_back(candidates[i]);
back_tracking(candidates, target, sum, i);
sum -= candidates[i];
path.pop_back();
}
return;
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
back_tracking(candidates, target, 0, 0);
return result;
}
总结
关键在于startIndex的使用,要实现多次取同一个元素。
40.组合总和2
题解
vector<int> path;
vector<vector<int>> result;
void back_tracking(vector<int>& candidates, int target, int sum, int startIndex, vector<bool> &used) {
if (sum == target) {
result.push_back(path);
return;
}
if (sum > target) {
return;
}
for (int i = startIndex; i < candidates.size(); i++) {
if (i > 0 && candidates[i] == candidates[i - 1] && !used[i - 1]) {
continue;
}
path.push_back(candidates[i]);
sum += candidates[i];
used[i] = true;
back_tracking(candidates, target, sum, i + 1, used);
used[i] = false;
sum -= candidates[i];
path.pop_back();
}
return;
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<bool> used(candidates.size(), false);
back_tracking(candidates, target, 0, 0, used);
return result;
}
总结
关键是去重操作。
131.分割回文串
题解
vector<string> path;
vector<vector<string>> result;
bool isTargrtStr(const string& str, int start, int end) {
for (int i = start, j = end; i <= j; i++, j--) {
if (str[i] != str[j]) {
return false;
}
}
return true;
}
void back_tracking(string s, int startIndex) {
if (startIndex >= s.size()) {
result.push_back(path);
return;
}
for (int i = startIndex; i < s.size(); i++) {
if (isTargrtStr(s, startIndex, i)) {
path.push_back(s.substr(startIndex, i - startIndex + 1));
} else continue;
back_tracking(s, i + 1);
path.pop_back();
}
return;
}
vector<vector<string>> partition(string s) {
back_tracking(s, 0);
return result;
}
总结
[startIndx, i]为待判断的子串。