Letter Combinations of a Phone Number
来源:互联网 发布:房屋平面图软件 编辑:程序博客网 时间:2024/04/28 07:29
Q:
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.
Solution:
DFS. Need to remove the last added letter when we find a combination.
public class Solution { static HashMap<Character, String> map = new HashMap<Character, String>(); static { map.put('2', "abc"); map.put('3', "def"); map.put('4', "ghi"); map.put('5', "jkl"); map.put('6', "mno"); map.put('7', "pqrs"); map.put('8', "tuv"); map.put('9', "wxyz"); } public List<String> letterCombinations(String digits) { List<String> combines = new ArrayList<String>(); if (digits == null) return combines; char[] charDigits = digits.toCharArray(); String output = ""; generate(charDigits, 0, output, combines); return combines; } public void generate(char[] input, int begin, String output, List<String> list) { if (begin == input.length) { list.add(new String(output)); return; } String letters = map.get(input[begin]); for (int i = 0; i < letters.length(); i++) { output = output + letters.substring(i, i+1); generate(input, begin+1, output, list); output = output.substring(0, output.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
- 算法学习----各种排序算法的实现和对比1
- Android中selector的使用
- [Leetcode] Sum Root to Leaf Numbers
- 股票数据查询接口
- eclipse编码设置
- Letter Combinations of a Phone Number
- Android_ScaleGestureDetector多点触控
- 火车票查询接口
- 构造函数,拷贝构造函数和析构函数
- C语言学习笔记——可变参数列表
- Robot Motion(递归+dfs)
- 笔试题之字符串是否符合给定词法
- java核心之集合框架——关系图
- 最大公约数和最小公倍数