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.
Solution: nothing but DFS (After finishing this one, you may feel better to solve problem Word Break II).
class Solution { public: void generator(string digits, vector<string>& ret, string s){ string dict[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; int n = digits.size(); if(n==0){ ret.push_back(s); return; } int curDigit = digits[0]-'0'; for(int i=0; i<dict[curDigit].size(); ++i){ generator(digits.substr(1, n-1), ret, s+dict[curDigit][i]); } } vector<string> letterCombinations(string digits) { // Note: The Solution object is instantiated only once and is reused by each test case. vector<string> ret; generator(digits, ret, ""); return ret; } };
No comments:
Post a Comment