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.

class Solution {
public:
    vector<string> letterCombinations(string digits) 
    {
        string code[]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        vector<string> result;
        if(digits.length()==0)
        {
            result.push_back("");
            return result;
        }
        
        string v;for(int i=0;i<digits.length();i++) v=v+" ";
        generate(code,result,v,digits,0);
        return result;
    }
    
    void generate(string* code,vector<string>& result,string& v,string& digits,int dep)
    {
        if(dep==digits.length())
        {
            result.push_back(v);
            return;
        }
        for(int i=0;i<code[digits[dep]-'0'].length();i++)
        {
            v[dep]=code[digits[dep]-'0'][i];
            generate(code,result,v,digits,dep+1);
        }
    }
}; 
posted @ 2014-05-29 15:36  erictanghu  阅读(114)  评论(0编辑  收藏  举报