C++ | Leetcode C++题解之第17题电话号码的字母组合

题目:

题解:

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();
            }
        }
    }
};

相关推荐

  1. LeetCode 17.电话号码字母组合

    2024-04-09 13:18:01       35 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-09 13:18:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-09 13:18:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-09 13:18:01       82 阅读
  4. Python语言-面向对象

    2024-04-09 13:18:01       91 阅读

热门阅读

  1. Linux C++ 024-STL初识

    2024-04-09 13:18:01       33 阅读
  2. 原生js封装请求组件

    2024-04-09 13:18:01       33 阅读
  3. ChatGPT革新学术论文写作:提升写作效率与质量

    2024-04-09 13:18:01       38 阅读
  4. 【算法】最长连续递增序列 - 贪心算法

    2024-04-09 13:18:01       30 阅读
  5. 渗透测试概述

    2024-04-09 13:18:01       37 阅读
  6. hadoop中hdfs的fsimage文件与edits文件

    2024-04-09 13:18:01       34 阅读