[leetcode] 17. Letter Combinations of a Phone Number

556 篇文章 2 订阅
441 篇文章 0 订阅

Description

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.
phone keyboard
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.

分析

题目的意思是:给定一串数字,然后求出所有的相应字母(如图)的字符串组合。

  • 就是一个深度优先搜索的问题,要注意循环函数的参数以及递归终止条件就行了。其他的没什么难度。

C++代码

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> res;
        if(digits.empty()){
            return res;
        }
        string dict[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        dfs(digits,0,dict,res,"");
        return res;
    }
    void dfs(string digits,int level,string dict[],vector<string> &res,string out){
        if(level==digits.size()){
            res.push_back(out);
        }else{
            string s=dict[digits[level]-'2'];
            for(int i=0;i<s.size();i++){
                out.push_back(s[i]);
                dfs(digits,level+1,dict,res,out);
                out.pop_back();
            }
        }
    }
};

Python代码

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        num_map={'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
        if(len(digits)==0):
            return []
        res=[]
        out=[]
        self.dfs(0,num_map,digits,res, out)
        return out
        
    def dfs(self,level,num_map, digits,res, out):
        if(level==len(digits)):
            out.append("".join(res))
            return 
        
        digit=digits[level]
        for s in num_map[digit]:
            res.append(s)
            self.dfs(level+1,num_map,digits,res,out)
            res.pop(-1) 

参考文献

[编程题]letter-combinations-of-a-phone-number
[LeetCode] Letter Combinations of a Phone Number 电话号码的字母组合

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值