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.
这道题让我们求电话号码的字母组合,即数字2到9中每个数字可以代表若干个字母,然后给一串数字,求出所有可能的组合,相类似的题目有 Path Sum II 二叉树路径之和之二,Subsets II 子集合之二,Permutations 全排列,Permutations II 全排列之二,Combinations 组合项, Combination Sum 组合之和和 Combination Sum II 组合之和之二等等。我们用递归Recursion来解,我们需要建立一个字典,用来保存每个数字所代表的字符串,然后我们还需要一个变量level,记录当前生成的字符串的字符个数,实现套路和上述那些题十分类似,代码如下:
解法一
// Recursion class Solution { public: vector<string> letterCombinations(string digits) { vector<string> res; if (digits.empty()) return res; string dict[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; letterCombinationsDFS(digits, dict, 0, "", res); return res; } void letterCombinationsDFS(string digits, string dict[], int level, string out, vector<string> &res) { if (level == digits.size()) res.push_back(out); else { string str = dict[digits[level] - '2']; for (int i = 0; i < str.size(); ++i) { out.push_back(str[i]); letterCombinationsDFS(digits, dict, level + 1, out, res); out.pop_back(); } } } };
这道题我们也可以用迭代Iterative来解,具体实现参见代码如下:
解法二
// Iterative class Solution { public: vector<string> letterCombinations(string digits) { vector<string> res; if (digits.empty()) return res; string dict[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; res.push_back(""); for (int i = 0; i < digits.size(); ++i) { int n = res.size(); string str = dict[digits[i] - '2']; for (int j = 0; j < n; ++j) { string tmp = res.front(); res.erase(res.begin()); for (int k = 0; k < str.size(); ++k) { res.push_back(tmp + str[k]); } } } return res; } };