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) {
        vector<string> str;//str for final resut
        string save;//save for temporary answer
        int convert[10] = {0, 3, 6, 9, 12, 15, 19, 22, 26};
        dfs(str, save, digits, 0, digits.size(), convert);
        return str;
        }
        void dfs(vector<string> &str, string save, 
             string dig, int now, int size, int *convert){
        if(now == size){
            str.push_back(save);
            return;
        }
        int tmp = dig[now] - '0' - 2;//change '2' to 0, '3' to 1...
        for(int i = convert[tmp]; i < convert[tmp+1]; i++){
            save.push_back('a' + i);//ex: a,b,c | d,e,f
            dfs(str, save, dig, now + 1, size, convert);
            save.pop_back();
        }
    }
};

 

posted on 2014-12-04 13:28  code#swan  阅读(93)  评论(0)    收藏  举报

导航