参考一篇总结
一般组合类问题都可以通过回溯法解决,如果能够画出组合决策树,有助于清晰思路。
这里的选择列表其实也就是每一层决策树的可选集合
class Solution {
private:
vector<string> res;
vector<string> kebord_record = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
public:
vector<string> letterCombinations(string digits) {
string tmp_str = "";
back_track(digits, 0, tmp_str);
return res;
}
void back_track(const string digits, int level_index, string tmp_str){
if(level_index==digits.length()){
res.push_back(tmp_str);
return;
}
for(int i=0; i<kebord_record[digits[level_index]-‘0‘].length(); i++){
tmp_str += kebord_record[digits[level_index]-‘0‘][i];
back_track(digits, level_index+1, tmp_str);
tmp_str.pop_back();
}
}
};
用户输入单词的时候,有可能输入错误,按错键盘比如说想输入a但是按成了a旁边的几个字母[zsg], 假定给一个用户的输出串和一套相对应的字母附近的候选集,求解所有可能的输入情况
假设输入是按顺序的,默认不存在顺序也错误的情况,比如先输入a,再输入b,不存在b a相反的情况
比如用户输入abm,候选字典{‘a‘:‘zsq‘,‘b‘:‘vghn‘,‘m‘:‘njkl‘,‘v‘:‘cfgb‘}
同样画出决策树,这是一个组合问题
#include <iostream>
#include<vector>
#include<string>
#include<map>
using namespace std;
class PossibleInputs{
private:
vector<string> res;
public:
vector<string> possible_inputs(string inputs, map<char, string> relation_neigbbors){
for(auto item:relation_neigbbors)
relation_neigbbors[item.first] = item.first+item.second;
string tmp_str = "";
back_track(0, inputs, tmp_str, relation_neigbbors);
return res;
}
void back_track(int tree_level, string inputs, string tmp_str,
map<char, string> relation_neigbbors){
if(tree_level==inputs.length()){
res.push_back(tmp_str);
return;
}
for(int i=0;i<relation_neigbbors[inputs[tree_level]].length();i++){
tmp_str += relation_neigbbors[inputs[tree_level]][i];
back_track(tree_level+1, inputs, tmp_str, relation_neigbbors);
tmp_str.pop_back();
}
}
};
int main(int argc, char const *argv[])
{
PossibleInputs pi;
map<char, string> relation_neigbbors = {{‘a‘,"zsq"},
{‘b‘,"vghn"},
{‘m‘,"njkl"},
{‘v‘,"cfgb"}
};
vector<string> res = pi.possible_inputs("abmvh",relation_neigbbors);
for(auto item:res)
cout<<item<<" ";
cout<<endl;
return 0;
}
原文:https://www.cnblogs.com/zhouyc/p/13406758.html