方法:回溯
class Solution {
private:
vector<vector<int>> res;
vector<int> path;
void dfs(vector<int> &candidates, int target, int cur, int idx) {
if (cur == target) {
res.emplace_back(path);
return;
}
for (int i = idx; i < candidates.size() && cur + candidates[i] <= target; ++i) {
path.emplace_back(candidates[i]);
dfs(candidates, target, cur + candidates[i], i);
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
res.clear();
path.clear();
sort(candidates.begin(), candidates.end());
dfs(candidates, target, 0, 0);
return res;
}
};
$时间复杂度O(n),空间复杂度O(target)
方法:回溯
class Solution {
private:
vector<vector<int>> res;
vector<int> path;
void dfs(vector<int>& candidates, int target, int cur, int idx) {
if (cur == target) {
res.emplace_back(path);
return ;
}
for (int i = idx; i < candidates.size() && cur + candidates[i] <= target; ++i) {
if (i > idx && candidates[i] == candidates[i-1]) continue;
path.emplace_back(candidates[i]);
dfs(candidates, target, cur + candidates[i], i+1);
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
res.clear();
path.clear();
sort(candidates.begin(), candidates.end());
dfs(candidates, target, 0, 0);
return res;
}
};
$时间复杂度O(×n),空间复杂度O(n)
方法:回溯+双指针
class Solution {
private:
vector<vector<string>> res;
vector<string> path;
bool ispalindrome(const string& s, int be, int ed) {
for (int l = be, r = ed; l < r; l++, r--) {
if (s[l] != s[r]) return false;
}
return true;
}
void dfs(const string& s, int idx) {
if (idx >= s.size()) {
res.emplace_back(path);
return ;
}
for (int i = idx; i < s.size(); ++i) {
if (ispalindrome(s, idx, i)) {
string str = s.substr(idx, i-idx+1);
path.emplace_back(str);
} else {
continue;
}
dfs(s, i + 1);
path.pop_back();
}
}
public:
vector<vector<string>> partition(string s) {
res.clear();
path.clear();
dfs(s, 0);
return res;
}
};
$时间复杂度不好分析,空间复杂度O(n)
方法:回溯+dp
class Solution {
private:
vector<vector<string>> res;
vector<vector<bool>> isPalindrome;
vector<string> path;
void computePalindcome(const string& s) {
isPalindrome.resize(s.size(), vector<bool>(s.size(), false));
for (int i = s.size() - 1; i>= 0; --i) {
for (int j = i; j < s.size(); ++j) {
if (i == j) {isPalindrome[i][i] = true;}
else if(j - i == 1) {isPalindrome[i][j] = (s[i] == s[j]);}
else {isPalindrome[i][j] = (s[i] == s[j] && isPalindrome[i+1][j-1]);}
}
}
}
void dfs(const string& s, int idx) {
if (idx >= s.size()) {
res.emplace_back(path);
return ;
}
for (int i = idx; i < s.size(); ++i) {
if (isPalindrome[idx][i]) {
string str = s.substr(idx, i-idx+1);
path.emplace_back(str);
} else {
continue;
}
dfs(s, i + 1);;
path.pop_back();
}
}
public:
vector<vector<string>> partition(string s) {
res.clear();
path.clear();
computePalindcome(s);
dfs(s, 0);
return res;
}
};
$时间复杂度O(×n),空间复杂度O(
)