题目:
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.
Answer 1: 递归方法(DFS)
思路:我们按照数字字符串的位数,逐一DFS拆解。得到第一位对应的字母之后,再继续DFS搜索,直到达到数字的位数为止。添加这个结果,并返回。
Attention:
1. 如何初始化数字字母查找表,用字符串数组表示。字符串数组一维坐标代表定位到第几个字符串,二维坐标代表定位到字符。如numap[3][2] = ‘f‘
string numap[] = {" ","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
2. 注意当digits为空输入时,我们要返回“”,而不是空数组。
string tmpstr(digits.size(), ' ');
3. 如果我们此时应用数字2对应的第一个字母,如何能在DFS后,巧妙地替换成数字2对应的其他字母呢?如果我们每次先push再pop, 只能pop最后一位的字符,不能准确定位,同时产生错误结果。我们这里用index 分别去更换新的字母。(index表示计算digits第几位)
tmpstr[index] = numap[digits[index] - '0'][i];
使用pop产生错误结果: tmpstr.pop_back();
Input: | "2" |
Output: | [" a"," b"," c"] |
Expected: | ["a","b","c"] |
Submitted Code
AC Code:
class Solution { public: vector<string> letterCombinations(string digits) { vector<string> ret; // if(digits.size() == 0) return ret; string tmpstr(digits.size(), ' '); letterCombinations_helper(digits, 0, tmpstr, ret); return ret; } private: vector<vector<char> > phonetable; void letterCombinations_helper(string digits, int index, string tmpstr, vector<string>& ret) { string numap[] = {" ","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; if(index == digits.size()) { ret.push_back(tmpstr); return; } for(int i = 0; i < numap[digits[index] - '0'].size(); i++) { tmpstr[index] = numap[digits[index] - '0'][i]; letterCombinations_helper(digits, index+1, tmpstr, ret); // tmpstr.pop_back(); } return; } };
Answer 2: 非递归方法(BFS)
思路:我们按照digits的位数,迭代的去求解结果,先从第一位的所有可能开始,不断扩充结果。思路有点类似于求subset.
举个例子,比如我们要求“23”,初始化ret = [""], 2对应三个字母,所以tmp会push三次,得到tmp[0] = "" + ‘a’; tmp[1] = "" + ‘b‘; tmp[2] = "" + ‘c‘. ret = tmp; (第一次最外层迭代结束); ret.size() = 3. tmp[0] = "a" + ‘d‘; tmp[1] = "a"+‘e‘; tmp[2] = "a"+‘f‘; tmp[3] = "b"+‘d’;.......直到得到所有的结果。(外层迭代结束)。每次都要更新目前为止的ret的所有结果,
下次迭代再在此基础上添加更多可能。
这种方法可能理解上有点难度,不太符合正常的思考过程,不过可以拓展编程思路。
Attention: 三层循环,最外层:digits的位数(digits.size()); 第二层: 当前ret内的子集数目(ret.size()); 最内层: 这个数字对应的所有可能字母(numap[digits[i] - ‘0‘].size()). 是BFS思路。
AC Code:
class Solution { public: vector<string> letterCombinations(string digits) { vector<string> ret(1, ""); string numap[] = {" "," ","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; for(int i = 0; i < digits.size(); i++) { vector<string> tmp; for(int j = 0; j < ret.size(); j++) { for(int k = 0; k < numap[digits[i]-'0'].size(); k++) { tmp.push_back(ret[j] + numap[digits[i]-'0'][k]); } } //更新ret ret = tmp; } return ret; } };
Submitted: 36 minutes ago |
Input: | "2" |
Output: | [" a"," b"," c"] |
Expected: | ["a","b","c"] |