[dfs] [iterative] letter combinations of a phone number
vector<string> letterCombinations(string digits) {
vector<string> dict = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> res;
DFS(dict, res, "", digits, 0);
return res;
}
// very concise!!!
void DFS(vector<string> &dict, vector<string> &res, string code, string digits, int kth) {
if(kth == digits.size()) {
res.push_back(code);
return;
}
int d = digits[kth] - '0';
string letters = dict[d];
for(int i=0; i<letters.size(); i++)
DFS(dict, res, code + letters[i], digits, kth+1);
}
// forget about below implentations
void combine(vector<string>& result, string digits, int level,
vector<string> summary, string tmp) {
if (level == digits.size()) {
result.push_back(tmp);
return;
}
string current_sum = summary[digits[level] - '2'];
for(int i = 0; i < current_sum.size(); i++) {
tmp.push_back(current_sum[i]);
combine(result, digits, level + 1, summary, tmp);
// c++ 11, used to be ==> tmp.erase(tmp.size()-1);
tmp.pop_back();
}
}
// iterative solution
vector<string> append_letters(vector<string> &res, const string& letters) { // use const?
vector<string> updated;
if(letters == "") {
updated = res;
return updated;
}
if(res.empty()) {
for(char c : letters) {
//updated.push_back("" + c); // cannot write "" + c. those two cannot be added!
string s = "";
updated.push_back(s + c);
}
} else {
for(string& s : res) {
for(char c : letters){
updated.push_back(s + c);
}
}
}
return updated;
}
vector<string> get_all_words_on_phone_number(const string& digits) {
vector<string> res;
if(digits.empty()) return res;
vector<string> vs = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
for(int i=0; i<digits.size(); i++) {
string letters = vs[digits[i] - '0'];
res = append_letters(res, letters);
}
return res;
}
int main()
{
vector<string> res = get_all_words_on_phone_number("234");
for(auto s : res) cout << s << "\n";
cout << ".";
}
/*
output:
adg
adh
adi
aeg
aeh
aei
afg
afh
afi
bdg
bdh
bdi
beg
beh
bei
bfg
bfh
bfi
cdg
cdh
cdi
ceg
ceh
cei
cfg
cfh
cfi
*/