【leetcode】Letter Combinations of a Phone Number

时间:2021-04-17 04:21:08

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.

【leetcode】Letter Combinations of a Phone Number【leetcode】Letter Combinations of a Phone Number

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.

回溯法递归调用即可:

 class Solution {

 public:

     vector<string> letterCombinations(string digits) {

         vector<string> num2string();

         num2string[]="";

         num2string[] = "";  

         num2string[] = "abc";  

         num2string[] = "def";  

         num2string[] = "ghi";  

         num2string[] = "jkl";  

         num2string[] = "mno";  

         num2string[] = "pqrs";  

         num2string[] = "tuv";  

         num2string[] = "wxyz";

         vector<string> result;

         string tmp="";

         combination(digits,,tmp,num2string,result);

         return result;

     }

     void combination(string &digits,int index,string tmp,vector<string> &num2string,vector<string> &result)

     {

         if(index==digits.length())

         {

             result.push_back(tmp);

             return;

         }

         string mapString=num2string[digits[index]-''];

         for(int i=;i<mapString.length();i++)

         {

             tmp.push_back(mapString[i]);

             combination(digits,index+,tmp,num2string,result);

             tmp.pop_back();

         }

     }

 };