给定一个数字字符串,返回数字可能表示的所有可能的字母组合。数字与字母的对应关系和手机按键对应。

本题源自LeetCode

----------------------------------------------

思路:

·1 枚举回溯。

 1 将所有的对应关系构建为一个map

2 用回溯法求解

代码:

 map numToStr={{2,"abc"},{3,"def"},{4,"ghi"},{5,"jkl"},{6,"mno"},{7,"pqrs"},{8,"tuv"},{9,"wxyz"}};
public:
    vector letterCombinations(string digits) {
        vector result;
        string tmp="";
        if(digits.length()==0){
            result.push_back(tmp);
            return result;
        }
        backPath(result,digits,tmp,0);
        return result;
    }
    
    void backPath(vector& result,string digits,string tmp,int index){
        if(index==digits.length()){
            result.push_back(tmp);
            return;
        }
        int k=digits[index]-'0';
        for(int i=0;i

代码 2  非递归

 vector letterCombinations(string digits) {
        vector result(1,"");
        map numToStr={{2,"abc"},{3,"def"},{4,"ghi"},{5,"jkl"},{6,"mno"},{7,"pqrs"},{8,"tuv"},{9,"wxyz"}};
        for(int i=0;i tmp;
            for(int j=0;j


你可能感兴趣的:(算法,C++,leetcode)