leetcode_[python/C++] 17.Letter Combinations of a Phone Number(手机号码字符组合)

本文介绍了LeetCode第17题,给定一个数字字符串,返回所有可能的字母组合。提供了使用Python和C++的递归解法,并探讨了处理特殊情况的技巧,包括空字符串和特定数字的处理。示例展示了如何从数字映射到字母并生成所有可能的组合。

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

题目链接
【题目】
Given a digit string, 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.
这里写图片描述

Input:Digit string “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.

Subscribe to see which companies asked this question


【分析】
思路:
1)递归
2)循环迭代
注意的点就是当输入为“”时,返回[ ]
当输入为“0”之类的还需要范围[“”]


递归
递归的写法有两种,一种是一个函数里面的递归写法,一种是引用另外的函数的写法
先贴下自己的代码,也就是第二种

class Solution {
public:
    vector<string> vec = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    vector<string> letterCombinations(string digits) {
        vector<string> ans;
        backtracking(ans, "", 0, digits);
        return ans;
    }
    void backtracking(vector<string>& ans, string str, int index, string& digits){
        if(str.size() == digits.size()){
            if(str.size() != 0) ans.push_back(str);
            return;
        }
        int id = digits[index] - '0';
        for(int i = 0; i < vec[id].size(); i++){
            backtracking(ans, str + vec[id][i], index + 1, digits);
        }
    }
};

第一种方法:
这是discuss中看到的,分享的原因是代码最后用了swap()函数,这样的拷贝是不需要占用内存的,特别好的想法

vector<string> letterCombinations(string digits) {
    vector<string> result;
    if(digits.empty()) return vector<string>();
    static const vector<string> v = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    result.push_back("");   // add a seed for the initial case
    for(int i = 0 ; i < digits.size(); ++i) {
        int num = digits[i]-'0';
        if(num < 0 || num > 9) break;
        const string& candidate = v[num];
        if(candidate.empty()) continue;
        vector<string> tmp;
        for(int j = 0 ; j < candidate.size() ; ++j) {
            for(int k = 0 ; k < result.size() ; ++k) {
                tmp.push_back(result[k] + candidate[j]);
            }
        }
        result.swap(tmp);
    }
    return result;
}

python
python当然很适合这道题目
先看下递归的写法:

class Solution(object):
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        m = {"2":"abc", "3":"def", "4":"ghi", "5":"jkl", "6":"mno", "7":"pqrs", "8":"tuv", "9":"wxyz"}
        ans = []
        if len(digits) == 0: return []
        if len(digits) == 1:
            return list(m[digits[0]])
        else:
            result = self.letterCombinations(digits[1:])
            for r in result:
                for j in m[digits[0]]:
                    ans.append(j + r)
        return ans

最后贴几个discuss上简洁的python写法:
递归:

class Solution(object):
def letterCombinations(self, digits):
    dic = {'0':' ', '1':'*', '2':'abc', '3':'def', '4':'ghi','5':'jkl', '6':'mno', '7':'pqrs', '8':'tuv', '9':'wxyz'} 
    return [a + b for a in dic.get(digits[:1], '') for b in self.letterCombinations(digits[1:]) or [''] ] or []

非递归:

class Solution(object):
def letterCombinations(self, digits):
    dic, res = {'0':' ', '1':'*', '2':'abc', '3':'def', '4':'ghi','5':'jkl', '6':'mno', '7':'pqrs', '8':'tuv', '9':'wxyz'} , []
    for x in digits:
        res = [pre + c for c in dic[x] for pre in res or ['']]
    return res
class Solution:
    def letterCombinations(self, digits):
        if '' == digits: return []
        kvmaps = {'2': 'abc','3': 'def','4': 'ghi','5': 'jkl','6': 'mno','7': 'pqrs','8': 'tuv','9': 'wxyz'}
        return reduce(lambda acc, digit: [x + y for x in acc for y in kvmaps[digit]], digits, [''])

这三个要特别注意的就是处理特殊情况:所以有or [ ] / or [”]的加入

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值