Recursive 1ms Java Solution


  • 1
    B
    public class Solution {
    public List<String> letterCombinations(String digits) {
        
        String[] lookup = new String[]{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 
        
        List<String> results = new ArrayList<>();
        generate("", digits, lookup, 0, results);
        return results;
    }
    
    private String generate(String prefix, String digits, String[] lookup, int index, List<String> collector) {
        if (index == digits.length()) return prefix;
        
        int digit = Character.getNumericValue(digits.charAt(index));
        String chars = lookup[digit];
        index++;
        
        for(int i = 0; i < chars.length(); i++) {
            String result = generate(prefix+chars.charAt(i), digits, lookup, index, collector);
            if (result != null) collector.add(result);
        }
        
        return null;
    }
    

    }


  • 0
    K

    This is the best solution for this problem, which is also easy to understand!!


Log in to reply
 

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