Description
Given a digit string, return all possible letter combinations that the number could represent.
Example
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”].
Analyse
这道题的背景也就是手机上的九宫格输入法假如根据它那个输入方式的话,能输出多少种结果,这也是一道简单的递归题,也不多解释。
Code
class Solution {
public:
const string DIGIT[8]={"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
void combination(vector<string> &ans, int pos, string &temp, string digits) {
if (pos == digits.length()) {
ans.push_back(temp);
} else {
int num = digits[pos] - '0';
for (int i = 0; i < DIGIT[num - 2].length(); i++) {
temp=temp + DIGIT[num - 2][i];
pos++;
combination(ans, pos, temp, digits);
pos--;
temp = temp.substr(0, temp.length() - 1);
}
}
}
vector<string> letterCombinations(string digits) {
vector<string> ans;
if (digits == "") return ans;
string temp = "";
combination(ans, 0, temp, digits);
return ans;
}
};