Java BackTracking Solution


  • 0
    public class Solution {
        private static final char[][] digitsAlphas = {
    		{}, 
    		{}, {'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) {
    	    List<String> result = new ArrayList<>();
    		if (digits == null || digits.length() == 0)
    			return result;
    		backtracking(result, new char[digits.length()], 0, digits);
    		return result;
    	}
    
    	private void backtracking(List<String> result, char[] temp, int track, String digits) {
    		char[] alphaForI = digitsAlphas[digits.charAt(track) - '0'];
    		for (int i = 0; i < alphaForI.length; i++) {
    			temp[track] = alphaForI[i];
    			if (track == digits.length() - 1) {
    				result.add(new String(temp));
    			} else {
    				backtracking(result, temp, track + 1, digits);
    			}
    		}
    	}
    
    }
    

Log in to reply
 

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