Leetcode:Question17

题目描述

在这里插入图片描述

题目解析

这道题目只需要简单的数字映射到字母即可。组合通过递归即可实现

代码

class Solution {
private:
    vector<string> res;     //存储最终的返回结果
    const string letterMap[10]{
        "",     //0 
        " ",    //1
        "abc",  //2
        "def",  //3
        "ghi",  //4
        "jkl",  //5
        "mno",  //6
        "pqrs", //7
        "tuv",  //8
        "wxyz"  //9
    };
    void findCombination(const string& digits, int index, const string& s){
        if(index == digits.size()){
            //保存结果
            res.push_back(s);
            return;
        }
        char c = digits[index]; //获取字符串中的指定位置的数字
        string letters = letterMap[c -'0']; //获取上述数字对应的字母
        for(int i =0; i < letters.size(); i++){ //遍历上述数字对应字母的每种可能性,然后对之后的数字字符串递归上述操作
            findCombination(digits, index + 1, s + letters[i]);
        }

    }
public:
    vector<string> letterCombinations(string digits) {
        res.clear();
        if(digits == "")
            return res;
        findCombination(digits, 0, "");
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/huangbx_tx/article/details/83477535
今日推荐