SHARE
TWEET

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

a guest Aug 19th, 2019 98 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Problem: https://leetcode.com/problems/letter-combinations-of-a-phone-number/solution/
  2. // Solution: https://www.youtube.com/watch?v=21OuwqIC56E
  3.  
  4. class Solution {
  5.     public List<String> letterCombinations(String digits) {
  6.         List<String> result = new ArrayList<String>();
  7.         if(digits == null || digits.length() == 0) {
  8.             return result;
  9.         }
  10.        
  11.         String[] mappings = {
  12.             "",
  13.             "",
  14.             "abc",
  15.             "def",
  16.             "ghi",
  17.             "jkl",
  18.             "mno",
  19.             "pqrs",
  20.             "tuv",
  21.             "wxyz"
  22.         };
  23.        
  24.         letterCombinationsRecursive(result, digits, "", 0, mappings);
  25.         return result;
  26.     }
  27.    
  28.     public void letterCombinationsRecursive(List<String> result, String digits, String current, int index, String[] mapping) {
  29.         if(index  == digits.length()) {
  30.             result.add(current);
  31.             return;
  32.         }
  33.        
  34.         String letters = mapping[digits.charAt(index) - '0'];
  35.         for(int i = 0; i < letters.length(); i++) {
  36.             letterCombinationsRecursive(result, digits, current + letters.charAt(i), index + 1, mapping);
  37.         }
  38.     }
  39.    
  40. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top