Monogram Leetcode of phone numbers

Title Description

Given a string contains only numeric characters 2-9, it can return all letter combinations indicated.

Given digital map to letters as follows (the same telephone key). Note 1 does not correspond to any alphabet.

Thinking

  1. Back: the nesting recursive loop
  2. Queue: First, the first number corresponding to the pressed character, starting from the second number, the first letter queue individually removed and after adding a second digit character corresponding to the queue to the tail

Code

method one:

class Solution {
public:
    vector<string> ans; // 设为全局变量,方便helper函数引用
    vector<string> sList={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; //字符表,注意不能用括号声明
    
    vector<string> letterCombinations(string digits) {
        if(digits.size()==0) return {};  // 特判
        helper(digits, {}, 0);
        return ans;
    }

    void helper(string digits, string s, int idx){
        if(idx==digits.size()){ // 回溯条件,保证digits全部被扫描
            ans.push_back(s);   // 将一种结果压入ans
            return;
        }
        else{
            // 依据digits的位数进行迭代,例如digits="234"
            // 第一层迭代为"2",将遍历对应的字符串"abc"并更新字符串,依次为"a","b","c"
            // 第二层迭代为"3",将遍历对应的字符串"def"并更新字符串,若上一层迭代为"a",则添加、更新为"ad", "ae"与"af".
            int pos=digits[idx]-'0';  // 获取idx在digits的字符,如“2”对应的2
            string tmpStr=sList[pos];  // 获取下标pos对应的字符串,如2对应的"abc"
            for(int i=0;i<tmpStr.size();i++){
                helper(digits,s+tmpStr[i],idx+1);   // 进行下一层迭代,注意同一层迭代时不改变s和idx等参数值
            }
        }
    }
};

Method Two:

class Solution {
public:
    vector<string> ans;
    vector<string> sList={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; //字符表
    
    vector<string> letterCombinations(string digits) {
        if(digits.size()==0) return {};  
        queue<string> q;
        for(int i=0;i<digits.size();i++){  // 遍历digits
            int pos=digits[i]-'0'; // 数字
            string s=sList[pos]; // 数字对应字符串
            if(i==0){
                string initStr;
                for(int j=0;j<s.size();j++){
                    initStr=s[j];
                    q.push(initStr); // 填入单字符
                }
            }
            else{
                string fr=q.front();    // 队列首位
                while(fr.size()<i+1){   // 队列首位的字符串是否小于遍历digits的子串的长度
                    q.pop();            // 删除首位
                    for(int j=0;j<s.size();j++){
                        q.push(fr+s[j]);
                    }
                    fr=q.front();       // 更新队列首位
                }
            }
        }
        while(!q.empty()){
            ans.push_back(q.front());
            q.pop();
        }
        return ans;
    }
};
Published 85 original articles · won praise 0 · Views 369

Guess you like

Origin blog.csdn.net/weixin_38312163/article/details/105078825