Letter Combinations of a Phone Number
来源:互联网 发布:知乎 一二级市场套利 编辑:程序博客网 时间:2024/06/09 22:02
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.
Have you met this question in a real interview?
思路:典型backtracking,建立一个mapping的数组,然后进行NP搜索,注意最后递归结束条件是sb.length() == digits.length(), 因为,如果用start ==digits.length(),比如"22", 因为外层循环会首先从最后一个数字开始,最后一个数字的index也是digits.length(),这样会加入 "a" "b" "c" 到结果里面,所以这里的遍历必须以StringBuilder的长度为结束条件比较准确。
public class Solution { public List<String> letterCombinations(String digits) { List<String> list = new ArrayList<String>(); if(digits == null || digits.length() == 0) return list; String[] mapArr = {"","","abc", "def", "ghi", "jkl","mno","pqrs","tuv","wxyz"}; StringBuilder sb = new StringBuilder(); collect(digits, sb, mapArr, 0, list); return list; } public void collect(String digits, StringBuilder sb, String[] mapArr, int start, List<String> list) { if( sb.length() == digits.length()){ list.add(sb.toString()); return; } for(int i=start; i<digits.length(); i++){ int index = digits.charAt(i)-'0'; String str = mapArr[index]; for(int j=0; j<str.length(); j++){ sb.append(str.charAt(j)); collect(digits, sb, mapArr, i+1, list); sb.deleteCharAt(sb.length()-1); } } }}
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
- LeetCode18:Letter Combinations of a Phone Number
- Letter Combinations of a Phone Number
- 【leetcode】Letter Combinations of a Phone Number
- LeetCode: Letter Combinations of a Phone Number
- Letter Combinations of a Phone Number
- Letter Combinations of a Phone Number
- [LeetCode]Letter Combinations of a Phone Number
- LeetCode-Letter Combinations of a Phone Number
- Letter Combinations of a Phone Number
- [LeetCode] Letter Combinations of a Phone Number
- Letter Combinations of a Phone Number
- LeetCode - Letter Combinations of a Phone Number
- LeetCode:Letter Combinations of a Phone Number
- 一个基于jQuery的弹出层插件XYTips
- Unity3d and automated builds
- 59A - Word
- Linux学习内容——我想学学完这些应该高手了
- Linux学习内容--我认为已经足够了
- Letter Combinations of a Phone Number
- .Class, Class.forName, .getClass()的区别
- Red and Black
- C++中的向上类型转换和向下类型转换
- C++中重定义、重写、重载的区别以及隐藏与覆盖的访问
- C++ 虚函数表解析
- C++中虚函数工作原理和(虚)继承类的内存占用大小计算
- C++ primer plus(第六版)学习笔记、习题答案(4.2)
- 数字图象处理之二维码图像提取算法(四)