LeetCode:17. Letter Combinations of a Phone Number

博客围绕LeetCode 17题,即九宫格输入法位置组合字符串问题展开。介绍了两种解题思路,一是暴力求解,用列表保存结果并拼接字符;二是回溯法,以递归形式固定位置字符,递归获取后续情况,最终得到所有可能组合。

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

LeetCode:17. Letter Combinations of a Phone Number

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.

题目的意思就是使用手机上的九宫格输入法输入一串位置,求出这些位置所能组合的所有字符串的情况。

思路一:暴力求解

用列表res保存当前位置之前的所有结果,然后遍历当前位置数字所表示的字符,拼接到res中保存的每个字符串。再赋值给res,最终返回res。

Python 代码实现

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        ans =[]
        numbers = {"2":"abc",
                  "3":"def",
                  "4":"ghi",
                  "5":"jkl",
                  "6":"mno",
                  "7":"pqrs",
                  "8":"tuv",
                  "9":"wxyz"}
        
        l = len(digits)
        
        if l == 0:
            return []
        
        res = []
        for c in numbers[digits[0]]:
            res.append(c)
        if l == 1:
            return res
        
        for i in range(1,l):
            tmp = []
            print(res)
            for c in numbers[digits[i]]:
                for content in res:
                    tmp.append(content+c)
            res = tmp    
        
        return res   
思路二:回溯法

和上面的方法总体是一样的,不过是以递归的形式写出的代码而已。就是每一步固定一个位置的字符,然后递归得到后面位置的所有情况,两个部分拼在一起。最终得到所有可能情况。

class Solution:
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        phone = {'2': ['a', 'b', 'c'],
                 '3': ['d', 'e', 'f'],
                 '4': ['g', 'h', 'i'],
                 '5': ['j', 'k', 'l'],
                 '6': ['m', 'n', 'o'],
                 '7': ['p', 'q', 'r', 's'],
                 '8': ['t', 'u', 'v'],
                 '9': ['w', 'x', 'y', 'z']}
                
        def backtrack(combination, next_digits):
            # if there is no more digits to check
            if len(next_digits) == 0:
                # the combination is done
                output.append(combination)
            # if there are still digits to check
            else:
                # iterate over all letters which map 
                # the next available digit
                for letter in phone[next_digits[0]]:
                    # append the current letter to the combination
                    # and proceed to the next digits
                    backtrack(combination + letter, next_digits[1:])
                    
        output = []
        if digits:
            backtrack("", digits)
        return output

THE END.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值