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.

Phone Keyboard

Figure: Phone Keyboard

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.

分析

递归

  1. // Letter Combinations of a Phone Number
  2. // 时间复杂度O(3^n),空间复杂度O(n)
  3. public class Solution {
  4. private static final String[] keyboard =
  5. new String[]{ " ", "", "abc", "def", // '0','1','2',...
  6. "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
  7. public List<String> letterCombinations(String digits) {
  8. List<String> result = new ArrayList<>();
  9. if (digits.isEmpty()) return result;
  10. dfs(digits, 0, "", result);
  11. return result;
  12. }
  13. private static void dfs(String digits, int cur, String path,
  14. List<String> result) {
  15. if (cur == digits.length()) {
  16. result.add(path);
  17. return;
  18. }
  19. final String str = keyboard[digits.charAt(cur) - '0'];
  20. for (char c : keyboard[digits.charAt(cur) - '0'].toCharArray()) {
  21. dfs(digits, cur + 1, path + c, result);
  22. }
  23. }
  24. }

迭代

  1. // Letter Combinations of a Phone Number
  2. // 时间复杂度O(3^n),空间复杂度O(1)
  3. public class Solution {
  4. private static final String[] keyboard =
  5. new String[]{ " ", "", "abc", "def", // '0','1','2',...
  6. "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
  7. public List<String> letterCombinations(String digits) {
  8. if (digits.isEmpty()) return new ArrayList<>();
  9. List<String> result = new ArrayList<>();
  10. result.add("");
  11. for (char d : digits.toCharArray()) {
  12. final int n = result.size();
  13. final int m = keyboard[d - '0'].length();
  14. // resize to n * m
  15. for (int i = 1; i < m; ++i) {
  16. for (int j = 0; j < n; ++j) {
  17. result.add(result.get(j));
  18. }
  19. }
  20. for (int i = 0; i < result.size(); ++i) {
  21. result.set(i, result.get(i) + keyboard[d - '0'].charAt(i/n));
  22. }
  23. }
  24. return result;
  25. }
  26. }

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/brute-force/letter-combinations-of-a-phone-number.html