216. 组合总和 III
方法:递归
class Solution {
private:
vector<vector<int>> res;
vector<int> path;
void solve(int k, int goal, int cur, int idx) {
if (cur > goal) return;
if (path.size() == k) {
if (cur == goal) res.push_back(path);
return ;
}
for (int i = idx; i <= 9-(k-path.size()) + 1; ++i) {
path.push_back(i);
solve(k, goal, cur + i, i + 1);
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum3(int k, int n) {
res.clear();
path.clear();
solve(k, n, 0, 1);
return res;
}
};
$时间复杂度O(*k),空间复杂度(n)
17. 电话号码的字母组合
方法:递归
class Solution {
private:
const string letterMap[10] = {
"",
"",
"abc",
"def",
"ghi",
"jkl",
"mno",
"pqrs",
"tuv",
"wxyz",
};
vector<string> res;
string str;
void solve(const string& digits, int idx, const string& str) {
if (idx == digits.size()) {
res.push_back(str);
return ;
}
int num = digits[idx] - '0';
string word = letterMap[num];
for (int i = 0; i < word.size(); ++i) {
solve(digits, idx + 1, str+word[i]);
}
}
public:
vector<string> letterCombinations(string digits) {
int n = digits.size();
if (!n) return res;
solve(digits, 0, str);
return res;
}
};
$时间复杂度O(),空间复杂度(n)