• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: 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"].

像这种DFS的题目,常见的写法无外乎两种,使用recursion, 或者用Stack。本文采用了Recursion的方式。做完后积累的经验有:像这种在一个ArrayList里面罗列可能的path的题目,recursion的参数一般包括:包含最终结果的集合(ArrayList),input(String),递归层次level(int),某一条具体的path(String)。最后这个参数虽然不是必须,但是如果使用了它,将会使recursion非常好写:所有关于这条路径的添加、删除、修改都可以以这个具体的path为操作对象,并且一旦条件满足,就可以把这个path添加到最终的结果集合里面去,用ArrayList add函数

 

Recursion:

Follow Up: 如果给你一个dictionary, 如何只返回在词典出现的combination。 如何做到最快,如何提高之前写的程序的runtime。

我的想法:给这个dictionary build一个Trie, time complexity O(nm), n is word count, m is average word length, 在10行recursion里面维护一个当前TrieNode, 下一跳可行的node必须是当前TrieNode的Non-null child, 可以在16行加一个If判断

 1    public class Solution {
 2         private static final String[] KEYS = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
 3     
 4         public List<String> letterCombinations(String digits) {
 5             List<String> res = new LinkedList<String>();
 6             combination("", digits, 0, res);
 7             return res;
 8         }
 9     
10         private void combination(String prefix, String digits, int offset, List<String> res) {
11             if (offset >= digits.length()) {
12                 res.add(prefix);
13                 return;
14             }
15             String letters = KEYS[(digits.charAt(offset) - '0')];
16             for (int i = 0; i < letters.length(); i++) {
17                 combination(prefix + letters.charAt(i), digits, offset + 1, ret);
18             }
19         }
20     }

Iteration: in Java

 1 public class Solution {
 2     public List<String> letterCombinations(String digits) {
 3         String[] data = new String[] { " ", "", "abc", "def", "ghi", "jkl",
 4                 "mno", "pqrs", "tuv", "wxyz" };
 5         List<String> ans = new ArrayList<String>();
 6         for (int i = 0; i < digits.length(); i++) {
 7             char[] c = data[digits.charAt(i) - '0'].toCharArray();
 8             List<String> sub = new ArrayList<String>();
 9             for (int j = 0; j < c.length; j++) {
10                 if (ans.isEmpty())
11                     ans.add("");
12                 for (String s : ans) {
13                     sub.add(s + c[j]);
14                 }
15                 
16             }
17             ans = sub;
18         }
19         return ans;
20     
21     }
22 }

 

 

 

 

posted @ 2014-06-11 02:24  neverlandly  阅读(671)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3