题目:
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.
class Solution {
public:
const char letterMap[10][5] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> letterCombinations(string digits) {
vector<string> res;
if(digits.empty()) return res;
string oneCombination;
letterCombinationsCore(digits, 0, oneCombination, res);
return res;
}
private:
void letterCombinationsCore(string digits, int index, string oneCombination, vector<string> &res){
if(index == digits.size()){
res.push_back(oneCombination);
return;
}
int num = digits[index]-'0';
int j = 0;
while(letterMap[num][j]){//典型的回溯的结构
oneCombination.push_back(letterMap[num][j]);
letterCombinationsCore(digits, index+1, oneCombination, res);
oneCombination.erase(oneCombination.size()-1, 1);
++j;//别忘了指针后移
}
}
};