LeetCode216
题目:
解法:
class Solution {
public:
vector<int> vec;
vector<vector<int>> result;
int sum(vector<int> vec){
int Sum = 0;
for(int i = 0;i < vec.size();i++){
Sum += vec[i];
}
return Sum;
}
void backtracing(int index,int k, int n){
if(vec.size() == k && sum(vec) == n){
result.push_back(vec);
return;
}
for(int i = index; i <= 9 ;i++){
vec.push_back(i);
backtracing(i + 1,k,n);
vec.pop_back();
}
}
vector<vector<int>> combinationSum3(int k, int n) {
int index = 1;
backtracing(index,k,n);
return result;
}
};
剪枝:
class Solution {
public:
vector<int> vec;
vector<vector<int>> result;
void backtracing(int index,int k, int target){
if(target < 0) return;
if(target == 0 && vec.size() == k){
result.push_back(vec);
return;
}
for(int i = index; i <= 9 ;i++){
vec.push_back(i);
if(vec.size() > k)
{
vec.pop_back();
return;
}
backtracing(i + 1,k,target - i);
vec.pop_back();
}
}
vector<vector<int>> combinationSum3(int k, int n) {
int index = 1;
backtracing(index,k,n);
return result;
}
};
LeetCode17
题目:
解法:
class Solution {
public:
vector<string> mad = {"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
vector<string> result;
string s;
void backtracing(string digits,int index1){
if(s.length() == digits.length()){
result.push_back(s);
return;
}
for(int j = 0 ;j < mad[digits[index1] -'2'].size();j++){
s.push_back( mad[digits[index1] -'2'][j]);
if(s.size() > digits.length()){
s.pop_back();
return;
}
backtracing(digits,index1 + 1);
s.pop_back();
}
}
vector<string> letterCombinations(string digits) {
if(digits.size() == 0) return result;
int index1 = 0;
backtracing(digits, index1);
return result;
}
};