Given a digit string, return all possible letter combinations that the number could represent.git
A mapping of digit to letters (just like on the telephone buttons) is given below.app
Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf","cd", "ce", "cf"]. Note: Although the above answer is lexicographical order, your answer could be in any order you want.函数
思路: 经典的backtracking解法。用HashMap存储数字对应的字母。而后就像subsets 同样。 这种题型都要利用返回void的helper函数,而后判断在什么条件的时候加入result中,而后在循环里面加入,递归再删除。对于这道题目, 当新生成的string的长度和digits的长度同样的时候就加入result里面。 而后for循环可能的char, 就是每一个数字对应的char[]里的元素。 ui
注意几点: string须要删减的时候用StringBuilder. 学一下如何新建带初始值的array。 code
时间复杂度:假设总共有n个digit,每一个digit能够表明k个字符,那么时间复杂度是O(k^n),就是结果的数量,因此是O(3^n)
空间复杂度:O(n)递归
public class Solution { public List<String> letterCombinations(String digits) { List<String> result = new ArrayList<String>(); if (digits == null || digits.length() == 0) { return result; } HashMap<Character, char[]> hash = new HashMap<Character, char[]>(); hash.put('0', new char[]{}); hash.put('1', new char[]{}); hash.put('2', new char[] { 'a', 'b', 'c' }); hash.put('3', new char[] { 'd', 'e', 'f' }); hash.put('4', new char[] { 'g', 'h', 'i' }); hash.put('5', new char[] { 'j', 'k', 'l' }); hash.put('6', new char[] { 'm', 'n', 'o' }); hash.put('7', new char[] { 'p', 'q', 'r', 's' }); hash.put('8', new char[] { 't', 'u', 'v'}); hash.put('9', new char[] { 'w', 'x', 'y', 'z' }); StringBuilder s = new StringBuilder(); helper(result, hash, s, digits,0); return result; } private void helper(List<String> result, HashMap<Character, char[]> hash, StringBuilder s, String digits, int i ) { if (digits.length() == s.length()) { result.add(s.toString()); return; } for (char c : hash.get(digits.charAt(i)) ) { s.append(c); helper(result,hash,s, digits, i + 1); s.deleteCharAt(s.length() - 1); } } }