Letter Combinations of a Phone Number
题目: 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”].
题意: 输入相似一串数字,返回可能出如今手机按键上的字母。上面有样例。
思路: 这样的不明白循环次数和范围的一般都是用回溯法(递归)来求解,用dfs(深度优先搜索)就可以。和八皇后问题相似。
代码:
string key_val[] = {
"0",
"1",
"abc",
"def",
"ghi",
"jkl",
"mno",
"pqrs",
"tuv",
"wxyz"};
class Solution {
public:
void dfs(
vector<string> &ret,
int dep,
string &cur_ret,
string digits){
if(dep == digits.size()){
ret.push_back(cur_ret);
return;
}
string cur_str = key_val[digits[dep]-
'0'];
for(
int i =
0; i < cur_str.size(); ++i){
cur_ret.push_back(cur_str[i]);
dfs(ret, dep+
1, cur_ret, digits);
cur_ret.pop_back();
}
}
vector<string> letterCombinations(
string digits){
vector<string>ret;
if(digits.size() ==
0){
return ret;
}
string cur_re(
"");
dfs(ret,
0, cur_re, digits);
return ret;
}
};
转载于:https://www.cnblogs.com/bhlsheji/p/5341560.html