Letter combination of leetcode phone number c++

Given a string containing only numbers 2-9, return all letter combinations it can represent.

The mapping of numbers to letters is given as follows (same as phone buttons). Note that 1 does not correspond to any letters.

Example:

输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Explanation:
Although the answers above are in lexicographical order, you can choose the order in which the answers are output.


Solution 1:

  • First calculate how many space counts are needed according to the idea of ​​combination, and then allocate the space size of res
  • Since res needs to change for every combination, an intermediate array temp is needed to assist the combination. Temp stores the data of the last res combination. According to temp, the data is recombined in res.

It's a bit difficult to understand, such as "23":

  • In the first step, we will get count=9; then res allocates 9 spaces
  • count=1; the latter is used to calculate the space size of the auxiliary array temp
  • When digits[i]=='2', temp allocates a space according to res to be empty, and finally res=[a,b,c];
  • 当digits[i]==‘3’,temp=[a,b,c],res=[aa,ab,ac,ba,bb,bc,ca,cb,cc]
class Solution {
public:
    vector<string> letterCombinations(string digits) {
        if(digits.size()==0) return {};
        map<char,string> a;//哈希表存放数字字母对应关系
        a.insert(map<char,string>::value_type('2',"abc"));
        a.insert(map<char,string>::value_type('3',"def"));
        a.insert(map<char,string>::value_type('4',"ghi"));
        a.insert(map<char,string>::value_type('5',"jkl"));
        a.insert(map<char,string>::value_type('6',"mno"));
        a.insert(map<char,string>::value_type('7',"pqrs"));
        a.insert(map<char,string>::value_type('8',"tuv"));
        a.insert(map<char,string>::value_type('9',"wxyz"));
        int count=1;
        for(int i=0;i<digits.size();i++)//计算空间大小
        {
            count*=a[digits[i]].size();
        }
        vector<string> res(count);
        count=1;//用来计算辅助空间大小
        for(int i=0;i<digits.size();i++)
        {
            int index=0;//用来记录组合时的下标
            vector<string> temp(res.begin(),res.begin()+count);
            for(int k=0;k<count;k++)
            {
                for(auto c:a[digits[i]])
                {
                    res[index]=temp[k]+c;
                    index++;
                }
            }
            count*=a[digits[i]].size();
        }
        return res;
    }
};

Guess you like

Origin blog.csdn.net/weixin_39139505/article/details/90265822