标签:detail tail list char letter ems ring width its
https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。
vector<string> letterCombinations(string digits) {}
使用回溯法,穷举所有可能的情况来得到解。
当遍历完所有数字时,产生结果
当探索到某一个数字时,遍历数字对应的所有字符:
?当前状态添加一个字符
?探索下一个数字
?还原当前状态
class Solution {
public:
map<char, string> letterMap = {
{‘2‘, "abc"}, {‘3‘, "def"}, {‘4‘, "ghi"}, {‘5‘, "jkl"},
{‘6‘, "mno"}, {‘7‘, "pqrs"}, {‘8‘, "tuv"}, {‘9‘, "wxyz"}
};
vector<string> result;
string current;
void backTrack(string digits, int index){
if(index == digits.size()){
result.push_back(current);
return;
}
char digit = digits[index];
string letters = letterMap[digit];
for(int i = 0; i < letters.size(); i++){
current.push_back(letters[i]);
backTrack(digits, index + 1);
current.pop_back();
}
}
vector<string> letterCombinations(string digits) {
if(digits.size() != 0){
backTrack(digits, 0);
}
return result;
}
};
class Solution {
Map<Character, String> letterMap = new HashMap<>(){
{
put(‘2‘, "abc");
put(‘3‘, "def");
put(‘4‘, "ghi");
put(‘5‘, "jkl");
put(‘6‘, "mno");
put(‘7‘, "pqrs");
put(‘8‘, "tuv");
put(‘9‘, "wxyz");
}
};
List<String> result = new ArrayList<>();
StringBuilder current = new StringBuilder().append("");
void backTrack(String digits, int index){
if(index == digits.length()){
result.add(current.toString());
return;
}
Character digit = digits.charAt(index);
String letters = letterMap.get(digit);
for(int i = 0; i < letters.length(); i++){
current.append(letters.charAt(i));
backTrack(digits, index + 1);
current.deleteCharAt(current.length() - 1);
}
}
public List<String> letterCombinations(String digits) {
if(digits.length() == 0){
return result;
}
backTrack(digits, 0);
return result;
}
}
标签:detail tail list char letter ems ring width its
原文地址:https://www.cnblogs.com/crazyBlogs/p/13159065.html