Letter Combinations of a Phone Number

来源:互联网 发布:samorost 3 mac 编辑:程序博客网 时间:2024/05/28 20:20

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、0和1无对应字母

2、7,9对应4个字母,其他3个。故而需取相应大小。


vector<string> letterCombinations(string digits) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.                string str[10]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};//前俩个为空!        vector<string> result;        string ans;        letter_dfs(digits,str,0,ans,result);        return result;    }        void letter_dfs(const string digits,const string *str,int index,string ans,vector<string> &result)    {       if(index == digits.size())        {           result.push_back(ans);           return ;       }       else       {                      for(int i=0;i<str[digits[index]-'0'].size();i++)//大小的确定           {               ans.push_back(str[digits[index]-'0'][i]);               letter_dfs(digits,str,index+1,ans,result);               ans.pop_back();               //以上可以用一句代替:(简化的话修改相应形参)               //letter_dfs(digits,str,index+1,ans+str[digits[index]-'0'][i],result);//技巧很强!           }       }    }



0 0
原创粉丝点击