其他分享
首页 > 其他分享> > 【Leetcode】17. 电话号码的字母组合

【Leetcode】17. 电话号码的字母组合

作者:互联网

文章目录

一. 题目信息

1. 描述

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
题目链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/

2. 示例

示例 1:
输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]

示例2:
输入:digits = ""
输出:[]

二. 解法

1. 回溯

算法思路:按照电话号码从前到后进行递归回溯

①. 复杂度分析

②. c++解法

class Solution {
public:
    unordered_map<char, string> table = {
        {'2', "abc"},
        {'3', "def"},
        {'4', "ghi"},
        {'5', "jkl"},
        {'6', "mno"},
        {'7', "pqrs"},
        {'8', "tuv"},
        {'9', "wxyz"}
    };
    vector<string> letterCombinations(string digits) {
        vector<string> colum;
        string item;
        if (digits.length() == 0) return colum;
        backtrace(digits, colum, 0, item);
        return colum;
    }
    void backtrace(string& digits, vector<string>& colum, int index, string& item) {
        if (index == digits.length()) colum.push_back(item);
        else {
            string s = table.at(digits[index]);
            for (const char& c : s) {
                item.push_back(c);
                backtrace(digits, colum, index + 1, item);
                item.pop_back();
            }
        }
    }
};

标签:digits,index,colum,17,示例,item,字母组合,Leetcode,string
来源: https://blog.csdn.net/weixin_44499369/article/details/117969239