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"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
解题思路:
题意给定一个数字字符串,返回可能由手机九空格输入法上字母的所有组合情况,顺序没有要求。
算法思路:
- 步骤1 如果数字字符串digits为空,则返回也为空;
- 步骤2 将0-9数字字符与手机上的九宫格输入法上的字符对应起来,即vector<string> s的建立映射关系;
- 步骤3 res保存上一个数字的最终结果,tmp保存当前数字的映射结果,将res中所有字符串与num中的所有字符逐一拼接,然后保存到tmp中,如此迭代,直到所有digits中的数字字符处理结束,详细见代码,好难表达;
代码如下:
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> res;
if(digits.length() == 0)
return res;
res.push_back("");
vector<string> s = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
for(int i = 0; i < digits.size(); i ++) {
string num = s[digits[i] - '0'];
vector<string> tmp;
for(int j = 0; j < num.length(); j ++) {
for(int k = 0; k < res.size(); k ++)
tmp.push_back(res[k] + num[j]);
}
res = tmp;
}
return res;
}
};