My accepted solution in Java (actually even I myself don't know how my code works....T_T.....)


  • 0
    H
    private final String[][] intToLetter = {
        {" "},
        {""},
        {"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"}
    };
    private int cycleLength = 0;
    private int listLength = 0;
    
    public List<String> letterCombinations(String digits) {
    	List<String> output = new ArrayList<String>();
    	
    	if(digits.length() != 0)
    		letter(digits, output);
    	
    	return output;
    }
    
    private void letter(String digits, List<String> output) {
    	if (digits.length() == 1) {
    		for (int i = 0; i < intToLetter[Integer.parseInt(digits)].length; i++)
    			output.add(intToLetter[Integer.parseInt(digits)][i]);
    		this.cycleLength = intToLetter[Integer.parseInt(digits)].length;
    		this.listLength += this.cycleLength;
    	}
    	else {
    		for (int i = 0; i < intToLetter[Integer.parseInt(digits.substring(0, 1))].length; i++) {
    			letter(digits.substring(1), output);
    			for (int j = this.listLength - this.cycleLength; j < this.listLength; j++)
    				output.set(j, intToLetter[Integer.parseInt(digits.substring(0, 1))][i] + output.get(j));
    		}
    		this.cycleLength *= intToLetter[Integer.parseInt(digits.substring(0, 1))].length;
    	}
    }

Log in to reply
 

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