|
| 1 | +/* |
| 2 | +
|
| 3 | +Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. |
| 4 | +
|
| 5 | +A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. |
| 6 | +
|
| 7 | +
|
| 8 | +
|
| 9 | +Example: |
| 10 | +
|
| 11 | +Input: "23" |
| 12 | +Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. |
| 13 | +Note: |
| 14 | +
|
| 15 | +Although the above answer is in lexicographical order, your answer could be in any order you want. |
| 16 | +
|
| 17 | +
|
| 18 | +Solution one is iterative, |
| 19 | +two is recursive |
| 20 | +*/ |
| 21 | +class Solution { |
| 22 | +public: |
| 23 | + vector<string> letterCombinations(string digits) { |
| 24 | + if (digits.empty()) return {}; |
| 25 | + vector<string> res{""}; |
| 26 | + vector<string> dict = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; |
| 27 | + for ( int i = 0; i < digits.size(); ++i ) |
| 28 | + { |
| 29 | + vector<string> temp; |
| 30 | + string tp = dict[digits[i] - '0']; |
| 31 | + for ( int j = 0; j < tp.size(); ++j ) |
| 32 | + for ( auto &a: res ) temp.push_back( a + tp[j] ); |
| 33 | + res = temp; |
| 34 | + } |
| 35 | + return res; |
| 36 | + } |
| 37 | +}; |
| 38 | + |
| 39 | +class Solution { |
| 40 | +public: |
| 41 | + vector<string> letterCombinations(string digits) { |
| 42 | + if (digits.empty()) return {}; |
| 43 | + vector<string> res; |
| 44 | + vector<string> dict = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; |
| 45 | + DFSCombine( dict, 0, "", res, digits ); |
| 46 | + return res; |
| 47 | + } |
| 48 | + void DFSCombine( vector<string>& dict, int level, string out, vector<string>& res, string digits ) |
| 49 | + { |
| 50 | + if ( level == digits.size() ) |
| 51 | + { |
| 52 | + res.push_back( out ); |
| 53 | + return; |
| 54 | + } |
| 55 | + string temp = dict[digits[level] - '0']; |
| 56 | + for ( int i = 0; i < temp.size(); ++i ) |
| 57 | + { |
| 58 | + DFSCombine( dict, level + 1, out + temp[i], res, digits ); |
| 59 | + } |
| 60 | + } |
| 61 | +}; |
0 commit comments