当前位置:网站首页>Backtracking - 17. Letter combinations of phone numbers
Backtracking - 17. Letter combinations of phone numbers
2022-07-26 00:05:00 【Xiao Zhao, who is working hard for millions of annual salary】
1 Title Description
Given a number only 2-9 String , Returns all the letter combinations it can represent . You can press In any order return .
The mapping of numbers to letters is given as follows ( Same as phone key ). Be careful 1 Does not correspond to any letter .
source : Power button (LeetCode)
link :https://leetcode.cn/problems/letter-combinations-of-a-phone-number
2 Title Example
Example 1:
Input :digits = “23”
Output :[“ad”,“ae”,“af”,“bd”,“be”,“bf”,“cd”,“ce”,“cf”]
Example 2:
Input :digits = “”
Output :[]
Example 3:
Input :digits = “2”
Output :[“a”,“b”,“c”]
3 Topic tips
0 <= digits.length <= 4
digits[i] Is the scope of [‘2’, ‘9’] A number of .
4 Ideas
First, use a hash table to store all possible letters corresponding to each number , And then do the backtracking operation .
Maintaining a string during backtracking , Represents an existing alphabetic arrangement ( If you don't traverse all the numbers of the phone number , The existing alphabetic arrangement is incomplete ). The string is initially empty . Take one digit of the phone number at a time , Get all possible letters corresponding to the number from the hash table , And insert one of the letters after the existing alphabet , Then continue to process the last digit of the phone number , Until all the numbers in the phone number are processed , That is to get a complete alphabetic arrangement . And then go back , Traverse the rest of the alphabet .
Backtracking algorithm is used to find all feasible solutions , If a solution is found to be infeasible , It will abandon the infeasible solution . In this question , Because every letter corresponding to every number can enter the alphabet , So there is no infeasible solution , Just enumerate all the solutions directly .
Complexity analysis
· Time complexity :O(3^m× 4^n), among m Is the input corresponding to 3 The number of letters ( Including digital 2、3、4、5、6、8),n Is the input corresponding to 4 The number of letters ( Including digital 7、9) , m+n Is the total number of input numbers . When the input contains m A correspondence 3 Two letter numbers and n A correspondence 4 It's a letter number , Different letter combinations — share 3m×4n Kind of , Need to traverse every — Alphabetic combination .
Spatial complexity :O(m + n), among m Is the input corresponding to 3 The number of letters ,n Is the input corresponding to 4 The number of letters ,m+n Is the total number of input numbers . In addition to the return value , The spatial complexity mainly depends on the hash table and the number of recursive calls in the backtracking process , The size of the hash table is independent of the input , You can think of it as a constant , The maximum number of recursive calls is m +n.
5 My answer
class Solution {
public List<String> letterCombinations(String digits) {
List<String> combinations = new ArrayList<String>();
if (digits.length() == 0) {
return combinations;
}
Map<Character, String> phoneMap = new HashMap<Character, String>() {
{
put('2', "abc");
put('3', "def");
put('4', "ghi");
put('5', "jkl");
put('6', "mno");
put('7', "pqrs");
put('8', "tuv");
put('9', "wxyz");
}};
backtrack(combinations, phoneMap, digits, 0, new StringBuffer());
return combinations;
}
public void backtrack(List<String> combinations, Map<Character, String> phoneMap, String digits, int index, StringBuffer combination) {
if (index == digits.length()) {
combinations.add(combination.toString());
} else {
char digit = digits.charAt(index);
String letters = phoneMap.get(digit);
int lettersCount = letters.length();
for (int i = 0; i < lettersCount; i++) {
combination.append(letters.charAt(i));
backtrack(combinations, phoneMap, digits, index + 1, combination);
combination.deleteCharAt(index);
}
}
}
}
Give a funny solution :
class Solution {
public List<String> letterCombinations(String digits) {
List<String> list = new ArrayList<>();
StringBuilder sb = new StringBuilder();
if(digits.length() == 0){
return list;
}
backtracking(digits, 0, list, sb);
return list;
}
public void backtracking(String digits, int index, List<String> list, StringBuilder sb){
if(sb.length() == digits.length()){
list.add(sb.toString());
return;
}
for(int i = index; i<digits.length(); i++){
char c = digits.charAt(i);
if(c == '2'){
sb.append('a');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
sb.append('b');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
sb.append('c');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
}else if(c == '3'){
sb.append('d');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
sb.append('e');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
sb.append('f');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
}else if(c == '4'){
sb.append('g');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
sb.append('h');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
sb.append('i');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
}else if(c == '5'){
sb.append('j');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
sb.append('k');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
sb.append('l');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
}else if(c == '6'){
sb.append('m');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
sb.append('n');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
sb.append('o');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
}else if(c == '7'){
sb.append('p');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
sb.append('q');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
sb.append('r');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
sb.append('s');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
}else if(c == '8'){
sb.append('t');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
sb.append('u');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
sb.append('v');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
}else if(c == '9'){
sb.append('w');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
sb.append('x');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
sb.append('y');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
sb.append('z');
backtracking(digits, i+1, list, sb);
sb.deleteCharAt(sb.length()-1);
}
}
}
}
边栏推荐
- Unity—欧拉角,四元数
- Exercise (3) create a list set (both ArrayList and LinkedList)
- 本轮牛市还能持续多久?|疑问解答 2021-05-11
- GUI interface of yolov3 (2) -- beautify the page + output the name and quantity of the identified object
- Vscode format JSON file
- [ManageEngine] servicedesk plus won the 2022 safety model engineering data safety award
- C language actual combat guessing game
- 二叉树——226. 翻转二叉树
- “群魔乱舞”,牛市是不是结束了?2021-05-13
- MySQL的DDL、DML和DQL的基本语法
猜你喜欢

Key features and application trends of next generation terminal security management

Find the cause of program dead cycle through debugging

多御安全浏览器手机版将增加新功能,使用户浏览更个性化

LeetCode高频题66. 加一,给你一个数组表示数字,则加1返回结果

NVIDIA cuDNN学习

Yolov4 tiny network structure

Dead letter queue and message TTL expiration code

VSCode格式化Json文件

Call nailing API and report an error: the signature sent by the robot is expired; Solution: please keep the signature generation time and sending time within timestampms

二叉树——226. 翻转二叉树
随机推荐
Vscode format JSON file
C语言实战之猜拳游戏
STM32 lighting procedure
LeetCode 沙胡同系列 -- 63. 不同路径 II
多御安全浏览器手机版将增加新功能,使用户浏览更个性化
Prometheus 运维工具 Promtool (二) Query 功能
Sequence traversal II of leetcode107 binary tree
Part 67: conversion between keypoint and point2f in opencv
C language implementation of three chess
LeetCode高频题66. 加一,给你一个数组表示数字,则加1返回结果
通货膨胀之下,后市如何操作?2021-05-14
二叉树相关知识
How to use yolov5 as an intelligent transportation system for red light running monitoring (1)
[ManageEngine] servicedesk plus won the 2022 safety model engineering data safety award
二叉树——104. 二叉树的最大深度
Stm32- analyze latency based on assembly
回溯——17. 电话号码的字母组合
BGR and RGB convert each other
SIGIR '22 recommendation system paper graph network
Piziheng embedded: the method of making source code into lib Library under MCU Xpress IDE and its difference with IAR and MDK