Java recursive easy to understand solution!Don't miss it!


  • 0
    C
     public List<String> letterCombinations(String digits) {
            if(digits.length() == 0) return Collections.EMPTY_LIST;
            
            HashMap<Character, String> lookup = new HashMap<>();
            lookup.put('1', "");
            lookup.put('2', "abc");
            lookup.put('3', "def");
            lookup.put('4', "ghi");
            lookup.put('5', "jkl");
            lookup.put('6', "mno");
            lookup.put('7', "pqrs");
            lookup.put('8', "tuv");
            lookup.put('9', "wxyz");
            lookup.put('0', "");
    
            List<String> result = new ArrayList<>();
            letterCombinations(digits, lookup, new StringBuilder(), result, 0);
    
            return result;
        }
        
        public void letterCombinations(String digits,Map<Character,String> lookup, StringBuilder partial, List<String> result, int offset) {
            //Exit case - we have recursed the length of the string.
            if (offset == digits.length()) {
                result.add(partial.toString());
                return;
            }
    
            //get the word for the number from lookup
            String word = lookup.get(digits.charAt(offset));
    
            if(word.length() == 0){
                letterCombinations(digits, lookup, partial, result, offset + 1);
            }
            else{
               //now go through each character of the word.
                for (int i = 0; i < word.length(); i++) {
                    //append
                    partial.append(word.charAt(i));
                    //with current character as base now recurse for next set of chars
                    letterCombinations(digits, lookup, partial, result, offset + 1);
                    //backtrack
                    partial.deleteCharAt(partial.length() - 1);
                }
            }   
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.