Java Backtracking soln incl cases for *, #,0,1 keys


  • 0
    T

    '''
    public class Solution {

    public static final char [][] digitMap = new char[][]{
        {' '},
        {},
        {'a','b','c'},
        {'d','e','f'},
        {'g','h','i'},
        {'j','k','l'},
        {'m','n','o'},
        {'p','q','r','s'},
        {'t','u','v'},
        {'w','x','y','z'},
        {'*'},
        {'#'}
    };
    
    public List<String> letterCombinations(String digits) {
        if(digits == null || digits.length() == 0)
            return Collections.emptyList();
            
        List<String> result = new ArrayList<String>();
        helper("", digits, result, 0);
        return result;
    }
    
    public void helper(String prefix, String digits, List<String> result, int start) {
        if(prefix.length() == digits.length()) {
            result.add(prefix);
            return;
        }
    
        int index = getNumVal(digits.charAt(start));
        for(int j = 0; j< digitMap[index].length; j++) {
            helper(prefix+digitMap[index][j], digits, result, start+1);
        }
    
    }
    
    public int getNumVal(char c) {
        if(c == '*')
            return 10;
        if(c== '#')
            return 11; 
        return Character.getNumericValue(c);
    }
    

    }

    '''


Log in to reply
 

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