17.Letter Combinations of a Phone Number
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.
思路:DFS,help函数生成第index个数字对应的字母。如果index=digits.length(),就将生成的字符串加入result数组。否则对digits[index]所有可能的字符加入elem,递归调用help函数。
-
class Solution { private: string temp[10]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; vector<string> result; public: void help(string digits,string elem,int index){ if(index==digits.length()){ result.push_back(elem); return; } int val = digits[index]-'0'; for(int i=0;i<temp[val].length();i++){ help(digits,elem+temp[val][i],index+1); } } vector<string> letterCombinations(string digits) { if(digits.length()==0) return result; help(digits,"",0); return result; } };
我的github:
https://github.com/zhoudayang