题目描述:(链接)
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.
解题思路:
递归方式,深度优先搜索
1 class Solution { 2 public: 3 vector<string> letterCombinations(string digits) { 4 vector<string> result; 5 if (digits == "") return result; 6 vector<string> keyboard {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 7 string midResult(digits.size(), ‘\0‘); 8 dfs(digits, 0, midResult, keyboard, result); 9 return result; 10 } 11 private: 12 void dfs(const string &digits, int index, string &midResult, const vector<string> &keyboard, vector<string> &result) { 13 if (index == digits.size()) { 14 result.push_back(midResult); 15 return; 16 } 17 18 char c = digits[index]; 19 for (int i = 0; i < keyboard[c - ‘0‘].size(); ++i) { 20 midResult[index] = keyboard[c - ‘0‘][i]; 21 dfs(digits, index + 1, midResult, keyboard, result); 22 } 23 } 24 };
[LeetCode]Letter Combinations of a Phone Number
原文:http://www.cnblogs.com/skycore/p/5077213.html