39. 组合总和
- 因为可以重复,传入
start_index
的值不需要+1了
class Solution {
public:
vector<int> path;
vector<vector<int>> result;
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
backtracking(candidates, target, 0);
return result;
}
void backtracking(vector<int>& candidates, int target, int start_idnex) {
int sum = 0;
for (auto n : path) {
sum += n;
}
if (sum > target) {
return;
}
if (sum == target) {
result.push_back(path);
return;
}
for (int i = start_idnex; i < candidates.size(); i++) {
path.push_back(candidates[i]);
backtracking(candidates, target, i);
path.pop_back();
}
}
};
40. 组合总和 II
- 需要用
used
数组来确认相同的数字有没有被用过
-
used[i - 1] == 0
代表这一层中这个数没被取过
class Solution {
public:
vector<int> path;
vector<vector<int>> result;
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<int> used(candidates.size(), 0);
sort(candidates.begin(), candidates.end());
backtracking(candidates, target, 0, used);
return result;
}
void backtracking(vector<int>& candidates, int target, int start_index,
vector<int> used) {
int sum = 0;
for (int n : path) {
sum += n;
}
if (sum > target) {
return;
}
if (sum == target) {
result.push_back(path);
return;
}
for (int i = start_index;
i < candidates.size() && sum + candidates[i] <= target; i++) {
if (i > 0 && candidates[i] == candidates[i - 1] &&
used[i - 1] == 0) {
continue;
}
used[i] = 1;
path.push_back(candidates[i]);
backtracking(candidates, target, i + 1, used);
path.pop_back();
used[i] = 0;
}
}
};
131. 分割回文串
-
statr_index
是回文串开始位置,i
是回文串结束位置
class Solution {
public:
vector<string> path;
vector<vector<string>> result;
vector<vector<string>> partition(string s) {
backtracking(s, 0);
return result;
}
void backtracking(string s, int start_index) {
if (start_index >= s.size()) {
result.push_back(path);
return;
}
for (int i = start_index; i < s.size(); i++) {
if (is_back_word(s, start_index, i)) {
string str = s.substr(start_index, i - start_index + 1);
path.push_back(str);
backtracking(s, i + 1);
path.pop_back();
}
}
}
bool is_back_word(string s, int start_index, int end_index) {
while (start_index < end_index) {
if (s[start_index] != s[end_index]) {
return false;
}
start_index++;
end_index--;
}
return true;
}
};