Advertisement
Guest User

17. Letter Combinations|Time:O(3^N*4^M)|Space: O(3^N*4^M)

a guest
Aug 19th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.37 KB | None | 0 0
  1. // Problem: https://leetcode.com/problems/letter-combinations-of-a-phone-number
  2. // Solution: https://leetcode.com/problems/letter-combinations-of-a-phone-number/solution/
  3.  
  4. class Solution {
  5.   Map<String, String> phone = new HashMap<String, String>() {{
  6.     put("2", "abc");
  7.     put("3", "def");
  8.     put("4", "ghi");
  9.     put("5", "jkl");
  10.     put("6", "mno");
  11.     put("7", "pqrs");
  12.     put("8", "tuv");
  13.     put("9", "wxyz");
  14.   }};
  15.  
  16.   List<String> output = new ArrayList<String>();
  17.  
  18.   public void backtrack(String combination, String next_digits) {
  19.     // if there is no more digits to check
  20.     if (next_digits.length() == 0) {
  21.       // the combination is done
  22.       output.add(combination);
  23.     }
  24.     // if there are still digits to check
  25.     else {
  26.       // iterate over all letters which map
  27.       // the next available digit
  28.       String digit = next_digits.substring(0, 1);
  29.       String letters = phone.get(digit);
  30.       for (int i = 0; i < letters.length(); i++) {
  31.         String letter = phone.get(digit).substring(i, i + 1);
  32.         // append the current letter to the combination
  33.         // and proceed to the next digits
  34.         backtrack(combination + letter, next_digits.substring(1));
  35.       }
  36.     }
  37.   }
  38.  
  39.   public List<String> letterCombinations(String digits) {
  40.     if (digits.length() != 0)
  41.       backtrack("", digits);
  42.     return output;
  43.   }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement