Letter Combinations of a Phone Number

来源:互联网 发布:我的淘宝展现词是0个 编辑:程序博客网 时间:2024/06/09 16:54

iven 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"].
对“0”的情况特殊处理;对digits对应的字符打表;然后递归枚举求解
class Solution {public:    vector<char> temp;    vector< vector<char> > ans;    string s[9] = {"","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};    void get_str(string digits, int index, int count)    {        if(temp.size() == count)        {            ans.push_back(temp);            return;        }        if(index >= count)            return;        int i ,j;        for(i = 0;i<s[digits[index]-'0'-1].length();i++)        {            temp.push_back(s[digits[index]-'0'-1][i]);            get_str(digits,index+1,count);            temp.pop_back();        }    }   vector< string > letterCombinations(string digits) {         int i,j = 0;         string num;         vector< string > ans1;         int len = 0;         if(digits == "")            return ans1;         for(i = 0;i<digits.length();i++)         {             if(digits[i] != '0')             {                 num= num +digits[i];                 len++;             }         }                 get_str(num,0,len);         for(i = 0;i<ans.size();i++)         {           string temp1;           for(j = 0;j<ans[i].size();j++)             temp1 = temp1 + ans[i][j];           ans1.push_back(temp1);         }         return ans1;    }};

0 0