LeetCode | #17 Letter Combinations of a Phone Number
来源:互联网 发布:linux启动java服务 编辑:程序博客网 时间:2024/06/01 08:26
题目:
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.
思路:
- 其实就是要遍历所有可能,从每个数字对应的字母中选一个,搭配在一起,如果用暴力枚举的话,还真不好搞而且会超时;
- 递归,关键的是要找规则,规则如下:
//digits-号码串 i-号码串的下标 temp-临时字符串 res-返回值public void dfs(String digits, int i, String temp, List<String> res)
- 初始条件:从号码串的第一个数字开始,定义临时字符串“”,定义要返回的List,开始递归,dfs(digits, 0, "", res);
- 如果号码串遍历完了,就返回List,否则获取该数字对应的字符串,遍历每个字母,添加到临时字符串中,并从号码串的下一个数字开始,递归调用,dfs(digits, i+1, temp2, res);
import java.util.ArrayList;import java.util.HashMap;import java.util.List;public class LetterCombinations {HashMap<Integer, String> map = new HashMap<Integer, String>(){{put(0, " ");put(1, "");put(2, "abc");put(3, "def");put(4, "ghi");put(5, "jkl");put(6, "mno");put(7, "pqrs");put(8, "tuv");put(9, "wxyz");}};public List<String> letterCombinations(String digits) {List<String> res = new ArrayList<>();dfs(digits, 0, "", res);return res; }//digits-号码串 i-号码串的下标 temp-临时字符串 res-返回值public void dfs(String digits, int i, String temp, List<String> res){if(i == digits.length()){res.add(temp);return;}String s = map.get(digits.charAt(i)-'0');for(int j=0; j< s.length(); j++){String temp2 = temp +s.charAt(j);dfs(digits, i+1, temp2, res);}}}
0 0
- LeetCode: Letter Combinations of a Phone Number
- LeetCode Letter Combinations of a Phone Number
- LeetCode: Letter Combinations of a Phone Number
- [Leetcode] Letter Combinations of a Phone Number
- [LeetCode] Letter Combinations of a Phone Number
- 【leetcode】Letter Combinations of a Phone Number
- LeetCode: Letter Combinations of a Phone Number
- [LeetCode]Letter Combinations of a Phone Number
- LeetCode-Letter Combinations of a Phone Number
- [LeetCode] Letter Combinations of a Phone Number
- LeetCode - Letter Combinations of a Phone Number
- LeetCode:Letter Combinations of a Phone Number
- LeetCode | Letter Combinations of a Phone Number
- leetcode Letter Combinations of a Phone Number
- Leetcode: Letter Combinations of a Phone Number
- 【leetcode】Letter Combinations of a Phone Number
- [LeetCode] Letter Combinations of a Phone Number
- leetcode: Letter Combinations of a Phone Number
- poj 2907 Collecting Beepers 邮递员问题暴力解法
- MFC 消息映射 消息传递MESSAGE_MAP 读深入浅出MFC感悟
- centos安装mysql以及mysql++开发环境
- jquery plugins demo
- Linux笔记_进程通讯——信号量
- LeetCode | #17 Letter Combinations of a Phone Number
- cocos3——7.使用UI的RichText
- java枚举和switch语法复习
- 获取当天时间信息
- 左旋字符串
- /etc/ld.so.conf文件
- 从零开始debian----给默认浏览器iceweasel安装flash插件
- Java静态块,静态成员变量,参数传递以及单例模式简单理解
- Linux笔记_多线程程序设计