17.Letter Combinations of a Phone Number(Back-Track)
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"].
思路I:iteration,广度优先。三重for循环,分别循环数字字符串、每个数字对应的字母、已有的result。时间复杂度O(n*3*(3^n))
class Solution { public: vector<string> letterCombinations(string digits) { if(digits=="") return result; m.clear(); m.insert(make_pair('2',"abc")); m.insert(make_pair('3',"def")); m.insert(make_pair('4',"ghi")); m.insert(make_pair('5',"jkl")); m.insert(make_pair('6',"mno")); m.insert(make_pair('7',"pqrs")); m.insert(make_pair('8',"tuv")); m.insert(make_pair('9',"wxyz")); result.push_back(""); int resultSize; for(int i = 0; i < digits.length(); i++){//traverse digits resultSize = result.size(); cout << "size= " << resultSize << endl; for(int j = 1; j < m[digits[i]].length(); j++){ //traverse the character in the digit(except first) for(int k = 0; k < resultSize; k++){ //traverse all current result result.push_back(result[k] + m[digits[i]][j]); } } for(int k = 0; k < resultSize; k++){ //deal with first digit: directly add in the current result result[k] += m[digits[i]][0]; } } return result; } private: unordered_map<char, string> m; vector<string> result; };
思路II: recursion,深度优先。将最外层循环转换成递归,递归的depth表示是第几个数字。每次遍历要加上当前数字对应的字母(for循环),加好后递归调用。
class Solution { public: vector<string> letterCombinations(string digits) { m.clear(); m.insert(make_pair('2',"abc")); m.insert(make_pair('3',"def")); m.insert(make_pair('4',"ghi")); m.insert(make_pair('5',"jkl")); m.insert(make_pair('6',"mno")); m.insert(make_pair('7',"pqrs")); m.insert(make_pair('8',"tuv")); m.insert(make_pair('9',"wxyz")); int len = digits.length(); dfs("", digits,0); return result; } void dfs(string s, string& digits, int depth){ char c = digits[depth]; for(int i = 0; i < m[c].length(); i++){ if(depth==digits.length()-1) { result.push_back(s+m[c][i]); } else dfs(s+m[c][i], digits, depth+1); } } private: unordered_map<char, string> m; //map是用红黑树实现查找,O(logn); unordered_map是用Hash table实现查找,O(1) vector<string> result; };