17. 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.

解题思路:一开始想的是递归,把7看错了,以为除了9都是3个字母,然后就没用map,而是把9特判了下,其他的用了个数学公式。后来发现自己蠢了。。

class Solution {
public:
    void dfs(string& digits,int st,int en, vector<string>&res,string temp){
        if(st==en){
            if(digits[st]=='7'){
                for(int i=0;i<4;i++)
                    res.push_back(temp+string(1,(char)'p'+i));
            }
            else if(digits[st]=='8'){
                for(int i=0;i<3;i++)
                    res.push_back(temp+string(1,(char)'t'+i));
            }
            else if(digits[st]=='9'){
                for(int i=0;i<4;i++)
                    res.push_back(temp+string(1,(char)'w'+i));
            }
            else {
                for(int i=0;i<3;i++)
                    res.push_back(temp+string(1,(char)(digits[st]-'2')*3+'a'+i));
            }
            return ;
        }
        if(digits[st]=='7'){
                for(int i=0;i<4;i++)
                    dfs(digits,st+1,en,res,temp+string(1,(char)'p'+i));
            }
            else if(digits[st]=='8'){
                for(int i=0;i<3;i++)
                    dfs(digits,st+1,en,res,temp+string(1,(char)'t'+i));
            }
            else if(digits[st]=='9'){
                for(int i=0;i<4;i++)
                   dfs(digits,st+1,en,res,temp+string(1,(char)'w'+i));
            }
            else {
                for(int i=0;i<3;i++)
                    dfs(digits,st+1,en,res,temp+string(1,(char)(digits[st]-'2')*3+'a'+i));
            }
        
    }
    vector<string> letterCombinations(string digits) {
        if(digits=="")return {};
        vector<string>res;
        dfs(digits,0,digits.length()-1,res,"");
        return res;
    }
};

还有一种就是两两combination

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        if(digits=="")return {};
        vector<string>res(1,"");
        vector<string>m={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        for(int i=0;i<digits.size();i++){
            int index=digits[i]-'0';
            vector<string>temp;
            for(int j=0;j<m[index].length();j++){
                for(int k=0;k<res.size();k++){
                    temp.push_back(res[k]+string(1,m[index][j]));
                }
            }
            res.swap(temp);
        }
        return res;
    }
};

 

posted @ 2017-09-27 10:24  Tsunami_lj  阅读(117)  评论(0编辑  收藏  举报