LeetCode 17. Letter Combinations of a Phone Number--笔试题--C++,Python解法

本文介绍了一种算法,用于生成电话按键对应的全部可能的字母组合。通过Python和C++实现,展示了如何遍历数字字符串,并根据电话键盘上的映射生成所有可能的字母组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目地址:Letter Combinations of a Phone Number - LeetCode


Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.

Example:

Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:

Although the above answer is in lexicographical order, your answer could be in any order you want.


这道题目是2019-9-16的XX笔试题,可惜自己没有早点做到。
题目是简单的。
Python解法如下:

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        s = {
            '1': '', '2': ['a', 'b', 'c'], '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'
        }
        res = ['']
        if digits == '':
            return []
        for i in digits:
            temp = []
            for j in res:
                for k in s[i]:
                    temp.append(j+k)
            res = temp
        return res

看到别人的一行解法如下:

from functools import reduce
class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        s = {
            '1': '', '2': ['a', 'b', 'c'], '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'
        }
        if digits=='': return []
        return reduce(lambda acc, digit: [x + y for x in acc for y in s[digit]], digits, [''])

C++解法如下:

class Solution {
public:
    vector<string> letterCombinations(string digits) {

        vector<string> result;
        if (digits.empty()) {
            return result;
        }
        string charmap[10] = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        result.emplace_back("");
        for (char digit : digits) {
            vector<string> temp;
            string chars = charmap[digit - '0'];
            for (const auto &j : result) {
                for (char c : chars) {
                    temp.push_back(j + c);
                }
            }
            result = temp;
        }
        return result;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值