LeetCode OJ-17.Letter Combinations of a Phone Number(DFS解法)
题目描述
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
题目理解
电话上的数字按键,从2-9每一个都有其相应的一组英文字母,题目要求从给定的输入数字串中,求解所有可能得到的字母组合情况。每一种字母组合情况的长度都与给定数字串长度相等,因此该条件则可以作为递归的结束条件,可以直接使用DFS解决,这里不会超时。思路类似全排列的求解,具体代码如下:
Code
void dfs(const string &digits, string &tmp, map<char, string> &keys,
vector<string> &res)
{
int cur_len = (int) tmp.length(); //已搜索到的其中一种组合方式的长度
if (cur_len == digits.length()) { //该长度等于digits的长度,说明该组合下的搜索完成
res.push_back(tmp);
return ;
}
else {
int i;
int len = (int) keys[digits[cur_len]].length();
for (i = 0; i < len; ++i) {
tmp.push_back(keys[digits[cur_len]][i]);
dfs(digits, tmp, keys, res);
tmp.pop_back(); //回溯的过程
}
}
}
vector<string> letter_combinations(const string &digits)
{
vector<string> res;
if (digits.length() < 1) { //没有按下任何数字键
return res;
}
string tmp("");
map<char, string> keys; //map用于记录2-9的数字按键上对应的英文字母
keys['2'] = string("abc");
keys['3'] = string("def");
keys['4'] = string("ghi");
keys['5'] = string("jkl");
keys['6'] = string("mno");
keys['7'] = string("pqrs");
keys['8'] = string("tuv");
keys['9'] = string("wxyz");
dfs(digits, tmp, keys, res);
return res;
}