Medium!
題目描述:
給定一個僅包含數字 2-9
的字符串,返回所有它能表示的字母組合。
給出數字到字母的映射如下(與電話按鍵相同)。注意 1 不對應任何字母。
示例:
輸入:"23" 輸出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
說明:
盡管上面的答案是按字典序排列的,但是你可以任意選擇答案輸出的順序。
解題思路:
這道題讓我們求電話號碼的字母組合,即數字2到9中每個數字可以代表若干個字母,然后給一串數字,求出所有可能的組合。
我們用遞歸Recursion來解,要建立一個字典,用來保存每個數字所代表的字符串,然后還需要一個變量level,記錄當前生成的字符串的字符個數。
C++參考答案一:
1 // Recursion 2 class Solution { 3 public: 4 vector<string> letterCombinations(string digits) { 5 vector<string> res; 6 if (digits.empty()) return res; 7 string dict[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};//建立一個字典,用來保存每個數字所代表的字符串 8 letterCombinationsDFS(digits, dict, 0, "", res); 9 return res; 10 } 11 void letterCombinationsDFS(string digits, string dict[], int level, string out, vector<string> &res) { 12 if (level == digits.size()) res.push_back(out); 13 else { 14 string str = dict[digits[level] - '2']; 15 for (int i = 0; i < str.size(); ++i) { 16 out.push_back(str[i]); 17 letterCombinationsDFS(digits, dict, level + 1, out, res); 18 out.pop_back(); 19 } 20 } 21 } 22 };
這道題我們也可以用迭代Iterative來解.
C++參考答案二:
1 // Iterative 2 class Solution { 3 public: 4 vector<string> letterCombinations(string digits) { 5 vector<string> res; 6 if (digits.empty()) return res; 7 string dict[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 8 res.push_back(""); 9 for (int i = 0; i < digits.size(); ++i) { 10 int n = res.size(); 11 string str = dict[digits[i] - '2']; 12 for (int j = 0; j < n; ++j) { 13 string tmp = res.front(); 14 res.erase(res.begin()); 15 for (int k = 0; k < str.size(); ++k) { 16 res.push_back(tmp + str[k]); 17 } 18 } 19 } 20 return res; 21 } 22 };