标签:leetcode
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"].
经典题目, iterative和recursive都要会写
iterative的是之前看的code ganker大神的解法,其实自己想也想得出来吧, 脑子太懒了
http://blog.csdn.net/linhuanmars/article/details/19743197
recursive的自己写了一下, 思路对了, 没能bug free
public class Solution { public List<String> letterCombinations(String digits) { List<String> res = new ArrayList<String>(); if(digits == null || digits.length() == 0) return res; Map<Character, String> map = new HashMap<Character, String>(); 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"); StringBuilder sb = new StringBuilder(); helper(res, digits, map, sb, 0); return res; } private void helper(List<String> res, String digits, Map<Character, String> map, StringBuilder sb, int index){ if(sb.length() == digits.length()){ res.add(sb.toString()); return; } String letters = map.get(digits.charAt(index)); for(int i = 0; i < letters.length(); i++){ sb.append(letters.charAt(i)); helper(res, digits, map, sb, index + 1); sb.deleteCharAt(sb.length() - 1); } } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
#leetcode#Letter Combinations of a Phone Number
标签:leetcode
原文地址:http://blog.csdn.net/chibaoneliuliuni/article/details/46754841