|
| 1 | +package pp.arithmetic.leetcode; |
| 2 | + |
| 3 | +import pp.arithmetic.Util; |
| 4 | + |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.List; |
| 7 | + |
| 8 | +/** |
| 9 | + * Created by wangpeng on 2019-04-09. |
| 10 | + * 17. 电话号码的字母组合 |
| 11 | + * <p> |
| 12 | + * 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。 |
| 13 | + * <p> |
| 14 | + * 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。 |
| 15 | + * |
| 16 | + * <image src="http://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Telephone-keypad2.svg/200px-Telephone-keypad2.svg.png"></image> |
| 17 | + * <p> |
| 18 | + * 示例: |
| 19 | + * <p> |
| 20 | + * 输入:"23" |
| 21 | + * 输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. |
| 22 | + * 说明: |
| 23 | + * 尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。 |
| 24 | + * |
| 25 | + * @see <a href="https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/">letter-combinations-of-a-phone-number</a> |
| 26 | + */ |
| 27 | +public class _17_letterCombinations { |
| 28 | + |
| 29 | + public static void main(String[] args) { |
| 30 | + _17_letterCombinations letterCombinations = new _17_letterCombinations(); |
| 31 | + Util.printStringList(letterCombinations.letterCombinations("23")); |
| 32 | + } |
| 33 | + |
| 34 | + char[][] map = new char[][]{ |
| 35 | + {'a', 'b', 'c'}, |
| 36 | + {'d', 'e', 'f'}, |
| 37 | + {'g', 'h', 'i'}, |
| 38 | + {'j', 'k', 'l'}, |
| 39 | + {'m', 'n', 'o'}, |
| 40 | + {'p', 'q', 'r', 's'}, |
| 41 | + {'t', 'u', 'v'}, |
| 42 | + {'w', 'x', 'y', 'z'} |
| 43 | + }; |
| 44 | + |
| 45 | + /** |
| 46 | + * 解题思路: |
| 47 | + * 这道题初看挺简单的,每一位对应的字母做个对应关系,弄个多项循环,但是代码实现还是很恶心的。 |
| 48 | + * 看了下题目关联的话题,有`回溯算法`,可以往这方面考虑 |
| 49 | + * 1、利用二维数组建立数字和字母的映射关系 |
| 50 | + * 2、深度遍历,一层层回溯得到结果 |
| 51 | + * <p> |
| 52 | + * 执行用时 : 1 ms, 在Letter Combinations of a Phone Number的Java提交中击败了100.00% 的用户 |
| 53 | + * 内存消耗 : 36.8 MB, 在Letter Combinations of a Phone Number的Java提交中击败了0.82% 的用户 |
| 54 | + * 内存上开销略大,二维数组可以变成一维字符串数组 |
| 55 | + * |
| 56 | + * @param digits |
| 57 | + * @return |
| 58 | + */ |
| 59 | + public List<String> letterCombinations(String digits) { |
| 60 | + List<String> retList = new ArrayList<>(); |
| 61 | + dfs(digits, 0, new char[digits.length()], retList); |
| 62 | + return retList; |
| 63 | + } |
| 64 | + |
| 65 | + private void dfs(String digits, int index, char[] cs, List<String> retList) { |
| 66 | + if (digits.length() == 0) return; |
| 67 | + if (index >= digits.length()) { |
| 68 | + retList.add(new String(cs)); |
| 69 | + return; |
| 70 | + } |
| 71 | + char c = digits.charAt(index); |
| 72 | + char[] maps = map[c - '2']; |
| 73 | + for (int i = 0; i < maps.length; i++) { |
| 74 | + cs[index] = maps[i]; |
| 75 | + dfs(digits, index + 1, cs, retList); |
| 76 | + } |
| 77 | + } |
| 78 | +} |
0 commit comments