【17】17. Letter Combinations of a Phone Number
17. Letter Combinations of a Phone Number
- Total Accepted: 125773
- Total Submissions: 384342
- Difficulty: Medium
- Contributors: Admin
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.
Solution1: (dfs) Recursive
1 class Solution { 2 public: 3 vector<string> n2l = {" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 4 5 vector<string> letterCombinations(string digits) { 6 vector<string> res; 7 if(digits.size() == 0){ 8 return res; 9 } 10 string level; 11 dfs(digits, res, level, 0); 12 return res; 13 } 14 15 void dfs(string digits, vector<string>& res, string& level, int start){ 16 //if(start == digits.size()){//base case 不对 17 if(level.size() == digits.size()){ 18 res.push_back(level); 19 return; 20 } 21 for(int i = start; i < digits.size(); i++){ 22 for(int j = 0; j < n2l[digits[i] - '0'].size(); j++){ 23 level += n2l[digits[i] - '0'][j]; 24 dfs(digits, res, level, i + 1); 25 //level -= n2l[digits[i] - '0'][j]; 26 level.resize(level.size() - 1); 27 } 28 } 29 //return res; 30 } 31 };
Solution 2: Iterative