1.组合
1.1 题目
. - 力扣(LeetCode)
1.2 题解
class Solution {
public:
//返回的结果
vector<vector<int>> result;
//结果中的组合
vector<int> path;
vector<vector<int>> combine(int n, int k)
{
Backtracking(n,k,1);
return result;
}
void Backtracking(int n,int k,int index)
{
//终止条件,收集结果
if(path.size()==k)
{
result.push_back(path);
return;
}
//处理单层递归逻辑
for(int i=index;i<=n;i++)
{
path.push_back(i);
Backtracking(n,k,i+1);
path.pop_back();
}
}
};
2.组合总和III
2.1 题目
. - 力扣(LeetCode)
2.2 题解
class Solution {
public:
vector<vector<int>> result;
vector<int> path;
vector<vector<int>> combinationSum3(int k, int n)
{
backtracking(k,n,1);
return result;
}
int sum(vector<int>& vec)
{
int sum=0;
for(auto i:vec)
{
sum+=i;
}
return sum;
}
void backtracking(int k,int n,int index)
{
//确定终止条件
if(path.size()==k)
{
if(sum(path)==n)
{
result.push_back(path);
}
return;
}
//确定单层递归逻辑
for(int i=index;i<=9;i++)
{
path.push_back(i);
backtracking(k,n,i+1);
path.pop_back();
}
}
};
3.电话号码的字符组合
3.1 题目
. - 力扣(LeetCode)
3.2 题解
class Solution
{
public:
//生成一个映射数组,索引代表着数字对应的字符串
const string strlist[10] = { "","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz" };
string s;
vector<string> result;
vector<string> letterCombinations(string digits)
{
if (digits.empty())return {};
backtracking(digits, 0);
return result;
}
void backtracking(string& digits, int index)
{
//确定递归终止条件
if (index == digits.size())
{
result.push_back(s);
return;
}
//确定单层递归逻辑
//将当前遍历的数字字符串变为int型
int digit = digits[index] - '0';
//取出数字对应的字符集
string letters = strlist[digit];
for (int i = 0; i < letters.size(); i++)
{
s.push_back(letters[i]);
backtracking(digits, index + 1);
s.pop_back();
}
}
};