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.

 

Subscribe to see which companies asked this question

 
class Solution {
public:
    /*
     * 采用回溯
     * 映射, digits[i]表示对应的数字
     * a[i]表示所选取数字对应字母的下标
     * b[digits[i]][a[i]]表示 所选取的对应的字母
     * 遍历每一行的一个字母时,需要遍历下一行的所有字母
     * 如果选择好一个字母后,发现这个字母属于最后一个数组的,就输出解,并向后移动一位
     * 如果移动后列数等于len,就将上一行的列向后移动
     * 如果行数为0,列数等于len,就说明遍历完毕
     *
     */
    vector<string> letterCombinations(string digits) {
        int i = 0;
        int j = 0;
        //a[i]表示选取当前行的某个字母
        int a[10];
        for (j=0; j<10; j++) {
            a[j] = INIT_VAL;
        }
        string b[10]={"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        vector<string> res;
        int rows = digits.length();
        if (0 == rows) {
            return res;
        }

        while (i < rows) {
            //选取当前行的一个字母
            if (a[i] < (int)b[_covert_char_to_int(digits[i])].length()) {
                a[i]++;
            }
            //如果当前行的字母已经遍历完了,就将当前行的字母下标初始化
            //并将当前行设置为前一行,然后字母+1
            while (i > 0 && a[i] == (int)b[_covert_char_to_int(digits[i])].length()) {
                a[i] = INIT_VAL;
                i--;
                a[i]++;
            }
            //如果当前行为0,前字母已经遍历完了就退出
            if (i == 0 && a[i] == (int)b[_covert_char_to_int(digits[i])].length()) {
                break;
                //如果当前行为最后一行,就说明生成了一个满足解,保存
            } else if (i == rows - 1) {
                int k = 0;
                string one_str = "";
                for (k=0; k<rows; k++) {
                    one_str += b[_covert_char_to_int(digits[k])][a[k]];
                }
                printf("%s\n", one_str.c_str());
                res.push_back(one_str);
                //默认行数+1
            } else {
                i++;
            };
        }
        return res;
    }
    int _covert_char_to_int(char c) {

        return c - 48;
    }

private:
    const static int INIT_VAL = -1;
};

 

posted on 2016-01-06 20:36  walkwalkwalk  阅读(163)  评论(0编辑  收藏  举报

导航