|
| 1 | +package com.leosanqing.leetcode.medium.array; |
| 2 | + |
| 3 | +import java.util.LinkedList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +/** |
| 7 | + * @Author: rtliu |
| 8 | + * @Date: 2020/7/6 上午11:22 |
| 9 | + * @Package: com.leosanqing.leetcode.medium.array |
| 10 | + * @Description: ` ` Given a string containing digits from 2-9 inclusive, |
| 11 | + * ` ` return all possible letter combinations that the number could represent. |
| 12 | + * ` ` A mapping of digit to letters (just like on the telephone buttons) is given below. |
| 13 | + * ` ` Note that 1 does not map to any letters. |
| 14 | + * ` ` Example: |
| 15 | + * ` ` Input: '23' |
| 16 | + * ` ` Output: ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']. |
| 17 | + * @Version: 1.0 |
| 18 | + */ |
| 19 | +public class _17_letter_combinations_of_a_phone_number { |
| 20 | + |
| 21 | + public static void main(String[] args) { |
| 22 | + |
| 23 | + System.out.println(letterCombinations("5465768")); |
| 24 | + } |
| 25 | + |
| 26 | + public static List<String> letterCombinations(String digits) { |
| 27 | + char[] charArray = digits.toCharArray(); |
| 28 | + |
| 29 | + List<String> list = new LinkedList<>(); |
| 30 | + char[][] map = { |
| 31 | + {}, |
| 32 | + {}, |
| 33 | + {'a', 'b', 'c'}, |
| 34 | + {'d', 'e', 'f'}, |
| 35 | + {'g', 'h', 'i'}, |
| 36 | + {'j', 'k', 'l'}, |
| 37 | + {'m', 'n', 'o'}, |
| 38 | + {'p', 'q', 'r', 's'}, |
| 39 | + {'t', 'u', 'v'}, |
| 40 | + {'w', 'x', 'y', 'z'}, |
| 41 | + }; |
| 42 | + |
| 43 | + backtrack(charArray, list, map, new StringBuilder(), 0); |
| 44 | + return list; |
| 45 | + |
| 46 | + } |
| 47 | + |
| 48 | + |
| 49 | + private static void backtrack(char[] digits, List<String> list, char[][] map, StringBuilder sb, int offset) { |
| 50 | + if (offset == digits.length) { |
| 51 | + list.add(sb.toString()); |
| 52 | + return; |
| 53 | + } |
| 54 | + |
| 55 | + // 获得 map 的索引 |
| 56 | + int index = digits[offset] - '0'; |
| 57 | + // 遍历每个按键的所有情况 |
| 58 | + for (int i = 0; i < map[index].length; i++) { |
| 59 | + // 挨个追加值 |
| 60 | + sb.append(map[index][i]); |
| 61 | + backtrack(digits, list, map, sb, offset + 1); |
| 62 | + // 删除 |
| 63 | + sb.deleteCharAt(sb.length() - 1); |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments