欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

leetcode--17. Letter Combinations of a Phone Number

程序员文章站 2022-05-13 21:25:36
...

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

leetcode--17. Letter Combinations of a Phone Number


利用backtrace。当探到底时,可以push_back

class Solution {
public:
    
    unordered_map<char, string> hash;
    vector<string> ret;
    
    void bt(string digits, int index, string former_str) {
        char key = digits[index];
        string val = hash[key];
        for(int i = 0; i < val.length(); i++){
            string tmp_str = former_str + val[i];
            if(index == digits.length()-1) {
                ret.push_back(tmp_str);
            }
            else{
                bt(digits, index + 1, tmp_str);
            }
        }
    }
    
    
    vector<string> letterCombinations(string digits) {
        hash.insert({{'2',"abc"},{'3',"def"},{'4',"ghi"},{'5',"jkl"},{'6',"mno"},{'7',"pqrs"},{'8',"tuv"},{'9',"wxyz"}});  
        bt(digits, 0, "");
        return ret;
    }
};


相关标签: Leetcode backtrace