分段排列,有点像乘法原理,各个区间的顺序确定,但是区间的内部元素不确定,针对各个区间回溯,区间之间相互独立
cpp
class Solution {
public:
vector<string> res;
string resStr;
vector<string> chooseList;
void resInit(){
for(int i = 0;i< 10;i++){
string chooseStr ="";
switch(i){
case 2:{
chooseStr = "abc";
break;
}
case 3:{
chooseStr = "def";
break;
}
case 4:{
chooseStr = "ghi";
break;
}
case 5:{
chooseStr = "jkl";
break;
}
case 6:{
chooseStr = "mno";
break;
}
case 7:{
chooseStr = "pqrs";
break;
}
case 8:{
chooseStr = "tuv";
break;
}
case 9:{
chooseStr = "wxyz";
break;
}
default:
break;
}
chooseList.push_back(chooseStr);
}
}
bool isValid();
void traceback(string resStr,string & digits,int seq){
if(resStr.size() == digits.size()){
res.push_back(resStr);
return;
}
for(auto j : chooseList[(digits[seq] -'0')]){
resStr.push_back(j);
traceback(resStr,digits,seq+1);
resStr.pop_back();
}
}
vector<string> letterCombinations(string digits) {
resInit();
if(digits == ""){
return res;
}
traceback(resStr,digits,0);
return res;
}
};
无重组合,不可复取
cpp
class Solution {
public:
vector<vector<int>> res;
vector<int> resVec;
vector<int> chooseList;
void resInit(){
for(int i =0;i< 9;i++){
chooseList.push_back(i+1);
}
}
bool isValid();
void traceback(vector<int> resVec,vector<int> &chooseList,int &n,int &k,int sum,int start){
if(k == resVec.size()){
if(sum == n){
res.push_back(resVec);
}
return;
}
for(int i =start;i< chooseList.size();i++){
resVec.push_back(chooseList[i]);
traceback(resVec,chooseList,n,k,sum+chooseList[i],i+1);
resVec.pop_back();
}
}
vector<vector<int>> combinationSum3(int k, int n) {
resInit();
traceback(resVec,chooseList,n,k,0,0);
return res;
}
};