码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] 17. 电话号码的字母组合

时间:2020-09-17 17:29:41      阅读:23      评论:0      收藏:0      [点我收藏+]

标签:http   push   problem   order   length   不用   amp   back   vector   

17. 电话号码的字母组合

排列题目,很容易想到回溯。下面是ac代码。

class Solution {
private:
    vector<string> vstrs = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
public:
    void backtrack(vector<string>& ans, int idx, const string& s, string& str) {
        if(idx == s.size()){
            ans.push_back(str);
            str = "";  // 1
            return;
        }
        for(int i=0; i<vstrs[s[idx]-‘0‘].size(); ++i) {
            string bak = str;
            str += vstrs[s[idx]-‘0‘][i];
            backtrack(ans, idx+1, s, str);
            str = bak;  // 2
        }
    }

    vector<string> letterCombinations(string digits) {
        vector<string> ans;
        if(!digits.empty()){
            string str;
            backtrack(ans, 0, digits, str);
        }
        return ans;
    }
};

和官方题解比,官方的数字字母映射用的unordered_map。

1 处实际上不用把str清空

2 处用push_back pop_back更清楚一点

附官方C++题解

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> combinations;
        if (digits.empty()) {
            return combinations;
        }
        unordered_map<char, string> phoneMap{
            {‘2‘, "abc"},
            {‘3‘, "def"},
            {‘4‘, "ghi"},
            {‘5‘, "jkl"},
            {‘6‘, "mno"},
            {‘7‘, "pqrs"},
            {‘8‘, "tuv"},
            {‘9‘, "wxyz"}
        };
        string combination;
        backtrack(combinations, phoneMap, digits, 0, combination);
        return combinations;
    }

    void backtrack(vector<string>& combinations, const unordered_map<char, string>& phoneMap, const string& digits, int index, string& combination) {
        if (index == digits.length()) {
            combinations.push_back(combination);
        } else {
            char digit = digits[index];
            const string& letters = phoneMap.at(digit);
            for (const char& letter: letters) {
                combination.push_back(letter);
                backtrack(combinations, phoneMap, digits, index + 1, combination);
                combination.pop_back();
            }
        }
    }
};

[leetcode] 17. 电话号码的字母组合

标签:http   push   problem   order   length   不用   amp   back   vector   

原文地址:https://www.cnblogs.com/pusidun/p/13627455.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!