39. 组合总和
39. 组合总和
cpp
复制代码
class Solution {
vector<vector<int>> res;
vector<int> temp;
public:
void backtracing(vector<int>& candidates, int startIndex, int target, int sum){
if (sum > target) {
return;
}
if (sum == target) {
res.push_back(temp);
return;
}
//无重复元素 但是元素可以被多次使用
//不能往回搜索 下一轮搜索的起点依然是 i
for (int i = startIndex; i < candidates.size(); ++i) {
sum += candidates[i];
temp.push_back(candidates[i]);
backtracing(candidates, i, target, sum); //表示可以重复取当前的数
sum -= candidates[i];
temp.pop_back();
}
return ;
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
backtracing(candidates, 0, target, 0);
return res;
}
};
40.组合总和II
40.组合总和II
cpp
复制代码
class Solution {
vector<vector<int>> res;
vector<int> temp;
public:
void backtracing(vector<int>& candidates, int target, vector<bool>& used, int startIndex, int sum){
if(sum == target) {
res.push_back(temp);
return;
}
for(int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; ++i) {
// used[i - 1] == true,说明同一树枝candidates[i - 1]使用过
// used[i - 1] == false,说明同一树层candidates[i - 1]使用过
// 要对同一树层使用过的元素进行跳过
if( i > 0 && used[i - 1] == false && candidates[i] == candidates[i - 1]) {
continue;
}
used[i] = true;
sum += candidates[i];
temp.push_back(candidates[i]);
backtracing(candidates, target, used, i + 1, sum);
temp.pop_back();
sum -= candidates[i];
used[i] = false;
}
return;
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end()); //需要排序,符合条件的组合也是有序的,便于去掉重复组合
vector<bool> used(candidates.size(), false);
backtracing(candidates, target, used, 0, 0);
return res;
}
};
131.分割回文串
131.分割回文串
cpp
复制代码
class Solution {
private:
vector<vector<string>> res;
vector<string> temp;
void bactracing(const string& s, int startIndex) {
if (startIndex >= s.size()) {
res.push_back(temp);
return;
}
for (int i = startIndex; i < s.size(); ++i) {
if (isPalindrome(s, startIndex, i)) { // 是否是回文串
string str = s.substr(startIndex, i - startIndex + 1); // 获取子串
temp.push_back(str);
} else {
continue;
}
bactracing(s, i + 1);
temp.pop_back();
}
}
bool isPalindrome (const string& s, int left, int right) {
for (int i = left, j = right; i < j; ++i, --j) {
if (s[i] != s[j]) {
return false;
}
}
return true;
}
public:
vector<vector<string>> partition(string s) {
bactracing(s, 0);
return res;
}
};