My recursive Java solution


  • 0
    L
    private void combinate(List<String> result, char[][] mask, char[] digits, int index, String res) {
        if (digits.length == res.length()) {
            result.add(res);
        } else {
            char[] letters = mask[digits[index] - '0'];
            for (int i = 0; i < letters.length; i++) {
                res += letters[i];
                combinate(result, mask, digits, index + 1, res); 
                res = res.substring(0, index);
            }
        }
    }
    public List<String> letterCombinations(String digits) {
        List<String> result = new ArrayList<String>();
        if (digits.length() == 0) return result;
        //  2 => {'a', 'b', 'c'}, 3 => {'d', 'e', 'f'}
    	char[][] mask = {
    	        {}, {}, {'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'}
    	}; 
    	combinate(result, mask, digits.toCharArray(), 0, "");
    	return result;
    }

Log in to reply
 

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