class Solution {
private:
vector> res;
vector path;
void backtracking(vector& candidates, int target, int sum, int startIndex) {
if (sum > target) return;
if (sum == target) {
res.push_back(path);
return;
}
for (int i = startIndex; i < candidates.size(); i++) {
path.push_back(candidates[i]);
backtracking(candidates, target, sum + candidates[i], i);
path.pop_back();
}
}
public:
vector> combinationSum(vector& candidates, int target) {
res.clear();
path.clear();
backtracking(candidates, target, 0, 0);
return res;
}
};
不用在for中backtracking部分传入i + 1了,这样才能重复使用元素。
class Solution {
private:
vector> res;
vector path;
void backtracking(vector& candidates, int target, int sum, int startIndex, vector used) {
if (sum > target) return;
if (sum == target) {
res.push_back(path);
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]);
used[i] = true;
backtracking(candidates, target, sum + candidates[i], i + 1, used);
path.pop_back();
used[i] = false;
}
}
public:
vector> combinationSum2(vector& candidates, int target) {
path.clear();
res.clear();
vector used(candidates.size(), false);
sort(candidates.begin(), candidates.end());
backtracking(candidates, target, 0, 0, used);
return res;
}
};
used数组的作用:区分树层和树枝去重,在树枝内used是true,不会因为与上一个相同就排除掉结果;树层内used是false,会因为与上一个相同直接continue。
去重的基础:排序。
这里不使用used数组也是可以的,只需判断i是否大于startIndex。
不使用sum也可以,通过target==0来判断。
class Solution {
private:
vector path;
vector> res;
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 (isP(s, startIndex, i)) {
string str = s.substr(startIndex, i - startIndex + 1);
path.push_back(str);
}else {
continue;
}
backtracking(s, i + 1);
path.pop_back();
}
}
bool isP(const string& s, int start, int end) {
for (int i = start, j = end; i < j; i++, j--) {
if (s[i] != s[j]) return false;
}
return true;
}
public:
vector> partition(string s) {
path.clear();
res.clear();
backtracking(s, 0);
return res;
}
};