From : https://leetcode.com/problems/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"].
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> ans;
if(digits == "") return ans;
map<char, string> charts;
charts['2'] = "abc";
charts['3'] = "def";
charts['4'] = "ghi";
charts['5'] = "jkl";
charts['6'] = "mno";
charts['7'] = "pqrs";
charts['8'] = "tuv";
charts['9'] = "wxyz";
find(ans, digits, charts, "", 0);
return ans;
}
void find(vector<string>& ans, string dgits, map<char, string>& chts, string cur, int idx) {
if(cur.size() == dgits.size()) { ans.push_back(cur); return; }
string str = chts[dgits[idx]];
for(int i=0, sz=str.size(); i<sz; i++) {
cur += str[i];
find(ans, dgits, chts, cur, idx+1);
cur.pop_back();
}
}
};
本文详细阐述了如何解决电话号码对应的字母组合问题,并通过一个示例代码展示了解决过程。代码实现了一个类,用于根据输入的数字字符串返回所有可能的字母组合。
557

被折叠的 条评论
为什么被折叠?



