标签:digits map 17 combination unordered combinations 字母组合 LeetCode string
题目描述
给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
说明:尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number
思路解析
回溯法:
- 维护一个哈希表,用来查找数字对应的字母表;
- 维护一个字符串,初始化为空,每次取一位数字,并将该数字的其中一个可能的字母插入到该字符串中,直至取完所有数字,即可得到一个解,将该解存入最终输出的容器中;
- 回溯:回退一位数字,更新其可能的字母,回退至第一位,即遍历所有情况。
在C++中采用unordered_map
维护一个哈希表,unordered_map
与map
的区别在于,unordered_map
基于哈希表,其查找的时间复杂度为\(O(1)\),map
基于红黑树,具有有序性,对于需要大量修改map
中的内容时,map
的时间复杂度为\(O(\log n)\)。
本例题中只需要查找,用unordered_map
。
代码实现
class Solution {
private:
unordered_map<char, string> phoneMap{
{'2', "abc"},
{'3', "def"},
{'4', "ghi"},
{'5', "jkl"},
{'6', "mno"},
{'7', "pqrs"},
{'8', "tuv"},
{'9', "wxyz"}
};
public:
vector<string> letterCombinations(string digits) {
vector<string> combinations;
if(digits.empty()) return combinations;
string combination;
backtrack(combinations, digits, 0, combination);
return combinations;
}
void backtrack(vector<string> &combinations, string digits, int index, string &combination) {
if(index == digits.length()) {
combinations.push_back(combination);
return;
}
char digit = digits[index];
string letters = phoneMap.at(digit);
for(auto letter : letters) {
combination.push_back(letter);
backtrack(combinations, digits, index + 1, combination);
combination.pop_back();
}
}
};
标签:digits,map,17,combination,unordered,combinations,字母组合,LeetCode,string 来源: https://www.cnblogs.com/xqmeng/p/13788637.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。