1.组合
class Solution {
public:
void backtracking(int n, int k, int start)
{
if(path.size() == k)
{
ret.push_back(path);
return;
}
for(int i = start; i <= n-(k-path.size())+1; ++i)
{
path.push_back(i);
backtracking(n, k, i+1);
path.pop_back();
}
}
vector<vector
path.clear();
ret.clear();
backtracking(n, k, 1);
return ret;
}
private:
vector
vector<vector
};
-
组合总和II
class Solution {
public:
void backtracking(int k, int n, int sum, int start)
{
if(sum > n)
{
return;
}
if(path.size() == k)
{
if(sum == n)
{
ret.push_back(path);
return;
}
}
for(int i = start; i <= 9 - (k - path.size()) + 1; ++i)
{
sum += i;
path.push_back(i);
backtracking(k, n, sum, i+1);
sum -= i;
path.pop_back();
}
}
vector<vector> combinationSum3(int k, int n) {
backtracking(k, n, 0, 1);
return ret;
}
private:
vectorpath;
vector<vector> ret;
}; -
电话号码的字母组合
class Solution {
public:
void backtracking(string digits, int index){
if(index == digits.size())
{
ret.push_back(path);
return;
}
int digit = digits[index] - '0';
string str = letterMap[digit];
for(int i = 0; i < str.size(); ++i)
{
path.push_back(str[i]);
backtracking(digits, index+1);
path.pop_back();
}
}
vector
if(digits.size() == 0)
{
return ret;
}
backtracking(digits, 0);
return ret;
}
private:
vector
string path;
string letterMap[10] = {""
, ""
, "abc"
, "def"
, "ghi"
, "jkl"
, "mno"
, "pqrs"
, "tuv"
, "wxyz"};
};