博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
17. Letter Combinations of a Phone Number
阅读量:2352 次
发布时间:2019-05-10

本文共 1610 字,大约阅读时间需要 5 分钟。

题目

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.

pic
Example:

Input: “23”

Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].

思路

先用HashMap把键盘上的键值对存起来。但是怎样拼凑每个子字符串呢?肯定不能用brute force来解,输入稍微多一点就崩了。递归?subStr += recur()?

解答

leetcode solution 1: Backtracking(DFS) 回溯算法

自己的想法已经比较接近了,将问题拆解成子串、子串的子串、子串的子串的子串…

class Solution {
Map
phone = new HashMap
() {
{
put("2", "abc"); put("3", "def"); put("4", "ghi"); put("5", "jkl"); put("6", "mno"); put("7", "pqrs"); put("8", "tuv"); put("9", "wxyz"); }};//匿名内部类初始化 List
output = new ArrayList
(); public void backtrack(String combination, String next_digits) {
// if there is no more digits to check if (next_digits.length() == 0) {
output.add(combination); } // if there are still digits to check else {
String digit = next_digits.substring(0, 1); String letters = phone.get(digit); for (int i = 0; i < letters.length(); i++) {
String letter = phone.get(digit).substring(i, i + 1); backtrack(combination + letter, next_digits.substring(1)); // substring(n); 取从n到最后一位元素为子串 } } } public List
letterCombinations(String digits) {
if (digits.length() != 0) backtrack("", digits); return output; }}

一些思考

遇到Brute Force会变成指数型复杂度的问题,就想到DFS、BFS这种递归算法

转载地址:http://bfqvb.baihongyu.com/

你可能感兴趣的文章
Spring Cloud 2.x学习笔记:2、feign改进(Greenwich版本)
查看>>
SpringCloud 2.x学习笔记:3、Hystrix(Greenwich版本)
查看>>
SpringCloud 2.x学习笔记:4、Zuul(Greenwich版本)
查看>>
ajax提交JSON数组及Springboot接收转换为list类
查看>>
SpringCloud 2.x学习笔记:5、Config(Greenwich版本)
查看>>
RabbitMQ安装、配置与入门
查看>>
Java异常
查看>>
Ibatis代码自动生成工具
查看>>
ant build.xml教程详解
查看>>
彻底理解ThreadLocal
查看>>
localhost与127.0.0.1的区别
查看>>
windows下的host文件在哪里,有什么作用?
查看>>
操作系统之字符集
查看>>
OSI和TCP/IP
查看>>
【工具】人脸识别比对开放平台汇总
查看>>
基于DirectUI技术开发的发卡系统
查看>>
STM32 HAL库、标准外设库、LL库(STM32 Embedded Software)
查看>>
51和AVR单片机
查看>>
DSP开发板
查看>>
stm32标准外设库和芯片资料下载地址
查看>>