LeetCode17 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.(Medium)
分析:
很好的练习搜索的题目,可以用BFS和回溯法(DFS)两种方式来做一下练习。
自己写的时候没太想明白回溯的写法(参数,返回值等等),写的是BFS的解法,DFS参考的讨论区。
代码1:
1 class Solution { 2 public: 3 vector<string> letterCombinations(string digits) { 4 string digMap[10] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; 5 vector<string> v; 6 if (digits.size() == 0) { 7 return v; 8 } 9 queue<string> q; 10 for (int i = 0; i < digMap[digits[0] - '0'].size(); ++i) { 11 q.push(string(1,digMap[digits[0] - '0'][i] )); 12 } 13 for (int i = 1; i < digits.size(); ++i) { 14 int l = q.size(); 15 for (int j = 0; j < l; ++j) { 16 string temp1 = q.front(); 17 q.pop(); 18 for (int k = 0; k < digMap[digits[i] - '0'].size(); ++k) { 19 string temp2 = temp1 + digMap[digits[i] - '0'][k]; 20 q.push(temp2); 21 } 22 } 23 } 24 while (!q.empty()) { 25 v.push_back(q.front()); 26 q.pop(); 27 } 28 return v; 29 } 30 };
回溯法:
1 class Solution { 2 private: 3 string digMap[10] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; 4 void dfs(vector<string>& v, string& tempStr, int index, string& digits) { 5 if (index == digits.size()) { 6 v.push_back(tempStr); 7 return; 8 } 9 for (int i = 0; i < digMap[digits[index] - '0'].size(); ++i) { 10 //tempStr += digMap[digits[index] - '0'][i]; 11 tempStr.push_back(digMap[digits[index] - '0'][i]); //string的push_back和pop_back以前没用过 12 dfs(v,tempStr,index + 1,digits); 13 tempStr.pop_back(); 14 } 15 } 16 public: 17 vector<string> letterCombinations(string digits) { 18 vector<string> result; 19 if (digits.size() == 0) { 20 return result; 21 } 22 string tempStr; 23 dfs(result,tempStr,0,digits); 24 return result; 25 } 26 };