首页 > 代码库 > 【leetcode】Letter Combinations of a Phone Number
【leetcode】Letter Combinations of a Phone Number
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.
回溯法递归调用即可:
1 class Solution { 2 3 public: 4 5 vector<string> letterCombinations(string digits) { 6 7 vector<string> num2string(10); 8 9 num2string[0]="";10 11 num2string[1] = ""; 12 13 num2string[2] = "abc"; 14 15 num2string[3] = "def"; 16 17 num2string[4] = "ghi"; 18 19 num2string[5] = "jkl"; 20 21 num2string[6] = "mno"; 22 23 num2string[7] = "pqrs"; 24 25 num2string[8] = "tuv"; 26 27 num2string[9] = "wxyz";28 29 30 31 vector<string> result;32 33 string tmp="";34 35 combination(digits,0,tmp,num2string,result);36 37 return result;38 39 }40 41 42 43 44 45 void combination(string &digits,int index,string tmp,vector<string> &num2string,vector<string> &result)46 47 {48 49 if(index==digits.length())50 51 {52 53 result.push_back(tmp);54 55 return;56 57 }58 59 60 61 string mapString=num2string[digits[index]-‘0‘];62 63 for(int i=0;i<mapString.length();i++)64 65 {66 67 tmp.push_back(mapString[i]);68 69 combination(digits,index+1,tmp,num2string,result);70 71 tmp.pop_back();72 73 }74 75 }76 77 };
【leetcode】Letter Combinations of a Phone Number
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。