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.
暴力方法解题。之前使用 if if if,超时,改成if ... else if ... else if ... 4ms。减少不必要判断还是蛮有效果的。
class Solution { public: vector<string> re; vector<string> letterCombinations(string digits) { string result = ""; int index = 0; letter(digits ,index , result); return re; } void letter(string s ,int i,string result) { if(i >= s.length()) { re.push_back(result); return; } else if(s[i] == '2') { letter(s,i+1,result+'a'); letter(s,i+1,result+'b'); letter(s,i+1,result+'c'); } else if(s[i] == '3') { letter(s,i+1,result+'d'); letter(s,i+1,result+'e'); letter(s,i+1,result+'f'); } else if(s[i] == '4') { letter(s,i+1,result+'g'); letter(s,i+1,result+'h'); letter(s,i+1,result+'i'); } else if(s[i] == '5') { letter(s,i+1,result+'j'); letter(s,i+1,result+'k'); letter(s,i+1,result+'l'); } else if(s[i] == '6') { letter(s,i+1,result+'m'); letter(s,i+1,result+'n'); letter(s,i+1,result+'o'); } else if(s[i] == '7') { letter(s,i+1,result+'p'); letter(s,i+1,result+'q'); letter(s,i+1,result+'r'); letter(s,i+1,result+'s'); } else if(s[i] == '8') { letter(s,i+1,result+'t'); letter(s,i+1,result+'u'); letter(s,i+1,result+'v'); } else if(s[i] == '9') { letter(s,i+1,result+'w'); letter(s,i+1,result+'x'); letter(s,i+1,result+'y'); letter(s,i+1,result+'z'); } } };