17. Letter Combinations of a Phone Number
Description
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”].
Analysis
这道题的意思是求当前所给整型数组所对应的可能的英文字符组合。
我的做法是想将数字相对应的字符组合存储与一个字符串型的数组中。
之后进行迭代,将当前整型字符对应的可能的字母组合分别去整型字符串之前所有可能组成的字符串进行组合。
从而得到从一个位置开始到当前字符串时所有可能的字母组合字符串。一直循环到所给字符串最后一个字符得到结果。
Code
class Solution
{
public:
vector<string> letterCombinations(string digits) {
vector<string> res;
if(digits.size() == 0) return res;
string d[] = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
res.push_back("");
for (int i = 0; i < digits.size(); ++i)
{
vector<string> temp;
string str = d[digits[i] - '0'];
for (int j = 0; j < str.size();++j)
for (int k = 0; k < res.size();k++)
temp.push_back(res[k]+str[j]);
res = temp;
}
return res;
}
};