方法:递归
class Solution {
private:
vector<vector<int>> res;
vector<int> path;
void solve(vector<int>& candidates, int goal, int cur, int idx) {
if (cur == goal) {
res.push_back(path);
return ;
}
for (int i = idx; i < candidates.size() && cur + candidates[i] <= goal; ++i) {
path.push_back(candidates[i]);
solve(candidates, goal, cur + candidates[i], i);
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
res.clear();
sort(candidates.begin(), candidates.end());
solve(candidates, target, 0, 0);
return res;
}
};
$时间复杂度O(s),空间复杂度O(target)
方法:递归
class Solution {
private:
vector<vector<int>> res;
vector<int> path;
void solve(vector<int>& candidates, int goal, int cur, int idx) {
if (cur == goal) {
res.push_back(path);
return ;
}
for (int i = idx; i < candidates.size() && cur + candidates[i] <= goal; ++i) {
if (i > idx && candidates[i] == candidates[i-1]) continue;
path.push_back(candidates[i]);
solve(candidates, goal, cur+candidates[i], i+1);
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
res.clear();
sort(candidates.begin(), candidates.end());
solve(candidates, target, 0, 0);
return res;
}
};
$时间复杂度O(n*),空间复杂度O(n)
方法:递归
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(
)