simple java recursive solution


  • 0
    Z

    simple recursive solution using a temp char array

        char[][] letters = {{},{},{'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() < 1) return result;
            char[] array = digits.toCharArray();
            temp = new char[array.length];
            letterCombinationsCore(array, 0, result);
            return result;
        }
    
        char[] temp;
    
        public void letterCombinationsCore(char[] array, int index, List<String> result) {
            if(index == array.length) {
                result.add(new String(temp, 0, temp.length));
                return;
            }
            int letterIndex = array[index] - 48;
            for(int i=0; i<letters[letterIndex].length; i++) {
                temp[index] = letters[letterIndex][i];
                letterCombinationsCore(array, index + 1, result);
            }
        }
    

Log in to reply
 

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