[LeetCode] 17. Letter Combinations of a Phone Number

电话号码的字母组合。题意是给一个string,里面是数字,请返回所有可能的字母组合。例子,

Example:

Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

这是典型的backtracking回溯类的题目,一定要会。回溯类的题目一般都是带着一个prefix前缀,然后不断地尝试不同的组合直到最后的结果满足一定的情况,往往是长度满足情况。这道题有两种解法,其中第二种解法也是一定会考的

第一种解法是典型的回溯解法,会用到一个helper函数。递归函数的跳出条件就是遍历完了当前所有的数字。每当遍历一个数字的时候,拿出它背后所有的字母,比如2,就拿出abc来分别往结果集里面添加。如下图所示,

时间O(3^n)

空间O(3^n)

Java实现

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

第二种做法是类似树的层序遍历。一开始将一个空的字符串加入一个用linkedlist创建的队列,接着遍历input,拿到每一个数字,加入队列,弹出的时候,遵循先进先出的原则,弹出某个字母,再根据长度判断是否需要再attach新的字符。动图链接

时间O(3^n)

空间O(3^n)

Java实现

 1 class Solution {
 2     public List<String> letterCombinations(String digits) {
 3         LinkedList<String> res = new LinkedList<>();
 4         if (digits == null || digits.length() == 0) {
 5             return res;
 6         }
 7         String[] mapping = new String[] { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
 8         res.add("");
 9         for (int i = 0; i < digits.length(); i++) {
10             int num = digits.charAt(i) - '0';
11             while (res.peek().length() == i) {
12                 String t = res.remove();
13                 for (char s : mapping[num].toCharArray()) {
14                     res.add(t + s);
15                 }
16             }
17         }
18         return res;
19     }
20 }

猜你喜欢

转载自www.cnblogs.com/aaronliu1991/p/12551950.html
今日推荐