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"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

Solution: ...

 1 class Solution {
 2 public:
 3     vector<string> res;
 4     vector<string> letterCombinations(string digits) {
 5         string mapping[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
 6         res.clear();
 7         string s;
 8         letterCombinationsRe(digits, mapping, s);
 9         return res;
10     }
11 
12     void letterCombinationsRe(const string &digits, string mapping[], string &s)
13     {
14         if (s.size() == digits.size()) {
15             res.push_back(s);
16             return;
17         }
18         string &letters = mapping[digits[s.size()]-'2']; 
19         for (int i = 0; i < letters.size(); ++i) {
20             s.push_back(letters[i]);
21             letterCombinationsRe(digits, mapping, s);
22             s.pop_back();
23         }
24     }
25 };

 

posted @ 2014-04-24 01:52  beehard  阅读(129)  评论(0编辑  收藏  举报