Letter Combinations of a Phone Number
(原文链接:点击打开链接)
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"].
Solution:
使用递归算法来解决问题:
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> answer;
string letter[10] = {" ","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
if (digits.length() == 0) return answer;
else if (digits.length() == 1)
{
for(int a = 0; a < letter[digits[0] - '0'].length(); a++)
{
string s = "";
s += letter[digits[0] - '0'][a];
answer.push_back(s);
}
}
else
{
for(int a = 0; a < letter[digits[0] - '0'].length(); a++)
{
vector<string> temp = letterCombinations(digits.substr(1));
for (int b = 0; b < temp.size(); b++)
{
string s = letter[digits[0] - '0'][a] + temp[b];
answer.push_back(s);
}
}
}
return answer;
}
};