Leetcode刷题记录--17. 电话号码的字母组合(回溯)

这道题的解法类似于排列组合,将其视为树结构,并对其完成搜索。

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

示例:

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

通过观察,我们可以得知一下几点:

  • 每一层的节点:每一层的节点应该是digits字符串某一位的对应的数字,比如说“23”中的3,要得到这个数字大体有两种方式:
    一种是在每一次的函数调用中取字符串的第0位——s[0],调用下一层函数时再从原字符串中从第1位开始截取子串;s.substr(1)。
    一种是传递一个指针pos,指向当前所指的位置,每一层调用将指针向后移动

  • 每一层传递中记录一下当前已拼接的字符串str

  • 终止条件,这个递归的的终止条件可以有很多,这取决于你采用什么方式得到每一层的节点,可以判断截取后的子串长度是否为0,也可以判断pos的位置是否为digits的最后一位。

  • 映射可以用arr[index]即数组访问下标的方式实现,也可以用hashmap实现。
    代码如下:

class Solution {
private:
    string str="";
public:
    vector<string> letterCombinations(string digits) {
        vector<string> result;
        unordered_map<char,string> map;
  
        map.insert({'2',"abc"});
        map.insert({'3',"def"});
        map.insert({'4',"ghi"});
        map.insert({'5',"jkl"});
        map.insert({'6',"mno"});
        map.insert({'7',"pqrs"});
        map.insert({'8',"tuv"});
        map.insert({'9',"wxyz"});

        if(digits == "") return result;
        dfs(map, digits,result, 0);
        return result;

    }

    //每个子value都不同
    void dfs(unordered_map<char, string>& map, string digits, vector<string> &result, int pos){
        
        if(pos == digits.size()){
            result.push_back(str);
            return;
        }     
        string c = map[digits[pos]];
    // cout << "c=" << c << endl;
        for(char w:c){
            // cout << str << endl;
            str+= w;
            dfs(map, digits, result, pos+1);
            str.pop_back();
        }
        return;
        
    }
};
posted @ 2020-04-18 23:13  c_y_yuan  阅读(160)  评论(0编辑  收藏  举报