题目:
Given a string containing digits from A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. Example: Input: "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. |
给定一个仅包含数字 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。 示例: 输入:"23" 输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. |
思路:先建立一个映射表dict。在遍历数字时,在dict中取出数字对应的字符str。建立一个临时字符数组t,将str的每个字符都连接到 res的每个元素的后面。
class Solution {
public:
vector<string> letterCombinations(string digits) {
if(digits.empty()) return {};
vector<string> res{""};
string dict[]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
for(int i=0;i<digits.size();++i)
{
string str=dict[digits[i]-'0'];
vector<string> t;
for(int j=0;j<str.size();j++)
for(string s:res) t.push_back(s+str[j]);
res = t;
}return res;
}
};