• 作者: 负雪明烛
  • id: fuxuemingzhu
  • 个人博客:http://fuxuemingzhu.cn/
  • 个人公众号:负雪明烛
  • 本文关键词:电话号码, 字母组合,回溯法,题解,leetcode, 力扣,Python, C++, Java

题目地址:https://leetcode.com/problems/generate-parentheses/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.

Example:

  1. Input: "23"
  2. 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.

题目大意

在拨号键盘上按下了几个键,问能打出来的字符串的所有组合是多少。

解题方法

回溯法

依然是回溯法。要求所有的可能的字符串的组合。

有点类似784. Letter Case Permutation,不需要对index进行for循环,因为对index进行for循环产生的是所有可能的组合。而这两个题要求的组合的长度是固定的,每个位置都要有字母。

另外就是要判断一下path != '',原因是当 digits 为""的要求的结果是 [] ,而不是 [""]

Python代码如下:

  1. class Solution(object):
  2. def letterCombinations(self, digits):
  3. """
  4. :type digits: str
  5. :rtype: List[str]
  6. """
  7. kvmaps = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
  8. res = []
  9. self.dfs(digits, 0, res, '', kvmaps)
  10. return res
  11. def dfs(self, string, index, res, path, kvmaps):
  12. if index == len(string):
  13. if path != '':
  14. res.append(path)
  15. return
  16. for j in kvmaps[string[index]]:
  17. self.dfs(string, index + 1, res, path + j, kvmaps)

如果不新增函数,而是直接使用题目给出的函数,也可以很快写出代码。唯一要注意的是,当题目输入为""的时候,要返回{},那么for循环就没法遍历,所以我给他添加成了{""},这样循环就能进行了。

  1. class Solution {
  2. public:
  3. vector<string> letterCombinations(string digits) {
  4. if (digits.size() == 0) return {};
  5. vector<string> res;
  6. for (char d : board[digits[0]]) {
  7. auto next = letterCombinations(digits.substr(1));
  8. if (next.size() == 0)
  9. next.push_back("");
  10. for (string n : next) {
  11. res.push_back(d + n);
  12. }
  13. }
  14. return res;
  15. }
  16. private:
  17. unordered_map<char, string> board = {{'2', "abc"}, {'3', "def"}, {'4', "ghi"}, {'5', "jkl"}, {'6', "mno"}, {'7', "pqrs"}, {'8', "tuv"}, {'9', "wxyz"}};
  18. };

内置函数

使用python 自带的product笛卡尔乘积函数。

  1. from itertools import product
  2. class Solution(object):
  3. def letterCombinations(self, digits):
  4. """
  5. :type digits: str
  6. :rtype: List[str]
  7. """
  8. if not digits:
  9. return []
  10. kvmaps = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
  11. answer = []
  12. for each in product(*[kvmaps[key] for key in digits]):
  13. answer.append(''.join(each))
  14. return answer

循环

使用循环也能轻松把这个题目给搞定。使用结果数组res表示遍历到当前的位置已有的结果,那么再遍历下一个位置的时候,把这个位置能形成的所有结果和原来的进行两两组合。

python代码如下:

  1. class Solution(object):
  2. def letterCombinations(self, digits):
  3. """
  4. :type digits: str
  5. :rtype: List[str]
  6. """
  7. if digits == "": return []
  8. d = {'2' : "abc", '3' : "def", '4' : "ghi", '5' : "jkl", '6' : "mno", '7' : "pqrs", '8' : "tuv", '9' : "wxyz"}
  9. res = ['']
  10. for e in digits:
  11. res = [w + c for c in d[e] for w in res]
  12. return res

日期

2018 年 2 月 24 日
2018 年 12 月 21 日 —— 一周就要过去了
2019 年 1 月 8 日 —— 别熬夜,我都开始有黑眼圈了。。

【LeetCode】17. Letter Combinations of a Phone Number 电话号码的字母组合的更多相关文章

  1. [LeetCode] 17. Letter Combinations of a Phone Number 电话号码的字母组合

    Given a string containing digits from 2-9inclusive, return all possible letter combinations that the ...

  2. [LeetCode]17. Letter Combinations of a Phone Number电话号码的字母组合

    Given a string containing digits from 2-9 inclusive, return all possible letter combinations that th ...

  3. Leetcode 17. Letter Combinations of a Phone Number(水)

    17. Letter Combinations of a Phone Number Medium Given a string containing digits from 2-9 inclusive ...

  4. [LintCode] Letter Combinations of a Phone Number 电话号码的字母组合

    Given a digit string, return all possible letter combinations that the number could represent. A map ...

  5. [leetcode 17]Letter Combinations of a Phone Number

    1 题目: Given a digit string, return all possible letter combinations that the number could represent. ...

  6. Java [leetcode 17]Letter Combinations of a Phone Number

    题目描述: Given a digit string, return all possible letter combinations that the number could represent. ...

  7. Leetcode 17.——Letter Combinations of a Phone Number

    Given a digit string, return all possible letter combinations that the number could represent. A map ...

  8. [leetcode]17. Letter Combinations of a Phone Number手机键盘的字母组合

    Given a string containing digits from 2-9 inclusive, return all possible letter combinations that th ...

  9. [LeetCode] 17. Letter Combinations of a Phone Number ☆☆

    Given a digit string, return all possible letter combinations that the number could represent. A map ...

随机推荐

  1. HTML三层界面显示

    1.效果示意图 2.主要标签属性 3.实现代码 1.效果示意图 要实现类似如下效果:点击"大模态框",中间出现一层遮盖整个页面的半透明页面,最上面出现"Large mod ...

  2. Python | 迭代器与zip的一些细节

    首先抛出一个困扰本人许久的问题: nums = [1,2,3,4,5,6] numsIter = iter(nums) for _ in zip(*[numsIter]*3): print(_) pr ...

  3. linux 常用查看命令

    linux 常用查看命令 目录 linux 常用查看命令 linux 查看内存/进程-ps/top linux 查看磁盘存储-df linux 查看io读写-iotop linux 查看端口占用-ne ...

  4. SpringCloud微服务实战——搭建企业级开发框架(三十一):自定义MybatisPlus代码生成器实现前后端代码自动生成

      理想的情况下,代码生成可以节省很多重复且没有技术含量的工作量,并且代码生成可以按照统一的代码规范和格式来生成代码,给日常的代码开发提供很大的帮助.但是,代码生成也有其局限性,当牵涉到复杂的业务逻辑 ...

  5. 安全相关,CSRF

    先说下CSRF的定义 跨站请求伪造(英语:Cross-site request forgery),也被称为 one-click attack 或者 session riding,通常缩写为 CSRF ...

  6. 一条查询SQL查询语句的执行原理

    先熟悉一下浅而易懂SQL执行的流程图SQL查询过程七步曲 1.查询SQL发送请求 客户端将查询sql按照mysql通信协议传输到服务端.服务端接受到请求后,服务端单起一个线程执行sql 2.判断是否为 ...

  7. oracle 日期语言格式化

    TO_DATE ('17-JUN-87', 'dd-mm-yy', 'NLS_DATE_LANGUAGE = American')

  8. Tomcat源码分析 | 一文详解生命周期机制Lifecycle

    目录 什么是Lifecycle? Lifecycle方法 LifecycleBase 增加.删除和获取监听器 init() start() stop() destroy() 模板方法 总结 前言 To ...

  9. BigDecimal中要注意的一些事

    一.关于public BigDecimal(double val) BigDecimal中三个主要的构造函数 1 public BigDecimal(double val) 将double表示形式转换 ...

  10. python的随机森林模型调参

    一.一般的模型调参原则 1.调参前提:模型调参其实是没有定论,需要根据不同的数据集和不同的模型去调.但是有一些调参的思想是有规律可循的,首先我们可以知道,模型不准确只有两种情况:一是过拟合,而是欠拟合 ...