zoukankan      html  css  js  c++  java
  • 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
    ", 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;
    };
  • 相关阅读:
    nodeJs爬虫小程序练习
    promise
    node-并发控制
    高性能Js—数据存取
    javascript测试框架mocha
    npm、模块暴露,小知识点区别
    高性能Js-加载和执行
    Request对象获得参数方法:query和body方法
    nvm工具
    在express中提供静态文件笔记
  • 原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5106817.html
Copyright © 2011-2022 走看看