Letter Combinations of a Phone Number:深度优先和广度优先两种解法
Letter Combinations of a Phone Number
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.
解法一:深度优先解法
即backtracking方法,每次向下搜索直到触底。这种方法采用LIFO(后进后出),通过递归实现。
public class Solution { public List<String> letterCombinations(String digits) { LinkedList<String> rst = new LinkedList<String>(); if (digits == null || digits.length() == 0) { return rst; } String[] mapping = new String[]{"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; String temp = ""; helper(rst, temp, digits, mapping, 0); return rst; } public void helper(List<String> rst, String temp, String digits, String[] mapping, int index) { if (index == digits.length()) { rst.add(new String(temp)); return; } String s = mapping[Character.getNumericValue(digits.charAt(index))]; for (int i = 0; i < s.length(); i++) { temp += s.charAt(i); helper(rst, temp, digits, mapping, index + 1); temp = temp.substring(0, temp.length() - 1); } } }
解法二:广度优先解法
这种方法采用FIFO(先进先出),通过非递归方式实现。具体使用了LinkedList数据结构的add方法在list尾部插入,remove方法在list头部删除来实现FIFO。此外,还巧妙地运用了peek方法,每次新加元素时更新原有的每个结果。
public class Solution { public List<String> letterCombinations(String digits) { LinkedList<String> rst = new LinkedList<String>(); if (digits == null || digits.length() == 0) { return rst; } String[] mapping = new String[]{"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; rst.add(""); for (int i = 0; i < digits.length(); i++) { int m = Character.getNumericValue(digits.charAt(i)); while(rst.peek().length() == i) { String s = rst.remove(); for (char c: mapping[m].toCharArray()) { rst.add(s + c); } } } return rst; } }
值得思考的是,从直观上看第二种方法非递归应该运行效率更高,但实际两种方法的运行时间是一样的,都打败了46.02%的java submissions。
posted on 2016-05-14 17:05 ShinningWu 阅读(227) 评论(0) 编辑 收藏 举报