[LeetCode] Letter Combinations of a Phone Number

来源:互联网 发布:淘宝介入后卖家不举证 编辑:程序博客网 时间:2024/06/06 17:22
[Problem]

Given a digit string, return all possible letter combinationsthat the number could represent.

A mapping of digit to letters (just like on the telephonebuttons) is given below.

[LeetCode] Letter Combinations of a Phone Number - coder007 - Coder007的博客

Input:Digit string "23"Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:
Although the above answer is in lexicographical order, your answercould be in any order you want.


[Analysis]
使用map进行数字到字符串的映射,再递归。

[Solution]

class Solution {
public:
// combination letters
vector<string> combination(string digits, map<char, string> &letterTable){
vector<string> res;

// empty string
if(digits.length() <= 0){
res.push_back("");
return res;
}
// one digit string
else if(digits.length() == 1){
char ch = digits[0];
if(ch >= '0' && ch <= '9'){
string letters = letterTable[ch];
for(int i = 0; i < letters.length(); ++i){
res.push_back(letters.substr(i, 1));
}
}
}
else{
char ch = digits[0];
if(ch >= '0' && ch <= '9'){
string letters = letterTable[ch];
vector<string> r = combination(digits.substr(1, digits.length()-1), letterTable);
for(int i = 0; i < letters.length(); ++i){
for(int j = 0; j < r.size(); ++j){
res.push_back(letters.substr(i, 1) + r[j]);
}
}
}
}
return res;
}

// letter combinations
vector<string> letterCombinations(string digits) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

// letter table
map<char, string> letterTable;
letterTable['0'] = " ";
letterTable['1'] = "";
letterTable['2'] = "abc";
letterTable['3'] = "def";
letterTable['4'] = "ghi";
letterTable['5'] = "jkl";
letterTable['6'] = "mno";
letterTable['7'] = "pqrs";
letterTable['8'] = "tuv";
letterTable['9'] = "wxyz";

return combination(digits, letterTable);
}
};


 说明:版权所有,转载请注明出处。Coder007的博客
原创粉丝点击