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.
一道回溯题,这里主要是注意vector<string>
的初始化方法:
vector<string> maps[10] = {"0","1","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};//错误
string maps[10] = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; //正确
vector<string> maps = {"0","1","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};//正确
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> result;
if(digits.empty()) return result;
vector<string> maps = {"0","1","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
result.push_back("");
for(int i = 0 ; i < digits.size();i++){
vector<string> temp;
string str = maps[digits[i] - '0'];
for(int j = 0 ; j < str.size();j++){
for(int k = 0; k < result.size();k++){
temp.push_back(result[k] + str[j]);
}
}
result = temp;
}
return result;
}
};