Loading

【力扣】电话号码的组合(回溯法)

问题描述

image

class Solution {
public:
    vector<string> res;
    string path;
    // char A[26] = {'a','b','c','d','e','f','g',
    // 'h','i','j','k','l','m','n','o','p','q',
    // 'r','s','t','u','v','w','x','y','z'};
    const string letterMap[10] = {
        "", // 0
        "", // 1
        "abc", // 2
        "def", // 3
        "ghi", // 4
        "jkl", // 5
        "mno", // 6
        "pqrs", // 7
        "tuv", // 8
        "wxyz", // 9
    };
    //首先,数字字符和字母字符相对应的问题很难解决,所以需要定义一个char的二维数组来保存数字与字母的映射
    //另外,还需要把所给的字符串作为参数传入backtrace函数中,否则很难确定下一层递归的循环起点
    void backtrace(const string& digits, int pos){
        //这里的pos应该是字符串digits的下标
        //在lettermap里的下标应该是
        if(path.size() == digits.size()){
            res.push_back(path);
            return ;
        }
        int MapPos = digits[pos] - '0';
        for(int i = 0; i < letterMap[MapPos].size(); i++ ){
            path+=letterMap[MapPos][i];
            backtrace(digits, pos+1);
            path.pop_back();
        }
    }
    vector<string> letterCombinations(string digits) {
        res.clear();
        path.clear();
        if(digits.size() == 0){
            return res;
        }
        backtrace(digits, 0);
        return res;
    }
};

按照回溯的三个部分依次构建,注意区分在哪里是向下一层递归,在哪里是探索同层的下一个。
在backtrace函数中,for循环是为了穷尽一层内的所有可能,所以i的右边界应该是电话按键上某个数字对应的字母个数,而循环体里对backtrace的调用是向下一层递归。

posted @ 2024-03-07 12:22  SaTsuki26681534  阅读(19)  评论(0)    收藏  举报