【leetcode刷题笔记】Letter Combinations of a Phone Number

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.


 

题解:用一个二维数组map保存数字到字母的映射,然后深度优先递归搜索如下的一棵树(以"23"为例,树不完整)

代码如下:

复制代码
 1 public class Solution {
 2     public List<String> letterCombinations(String digits) {
 3         ArrayList<String> answer = new ArrayList<String>();
 4         
 5         char[][] map = {{'a','b','c'},{'d','e','f'},{'g','h','i'},{'j','k','l'},{'m','n','o'},{'p','q','r','s'},{'t','u','v'},{'w','x','y','z'}};
 6         String currentPath = new String();
 7         
 8         DeepSearch(map, answer, digits, currentPath);
 9         return answer;
10     }
11     
12     public void DeepSearch(char[][] map,List<String> answer,String digits,String currentPath){
13         if(digits.length() == 0)
14         {
15             String temp = new String(currentPath);
16             answer.add(temp);
17 
18             return;
19         }
20         
21         int now = digits.charAt(0) - '0';
22         for(int j = 0;j < map[now-2].length;j++){
23             currentPath += map[now-2][j];
24             DeepSearch(map, answer, digits.substring(1), currentPath);
25             currentPath = currentPath.substring(0, currentPath.length()-1);
26         }
27     }
28 }
复制代码

 

posted @   SunshineAtNoon  阅读(149)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示