Java Simple Recursive Solution:)


  • 0
    S
        public List<String> letterCombinations(String digits) {
            String[] numToChar = {"0","0","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
            return letterCombinations(digits, numToChar);
        }
        
        public List<String> letterCombinations(String digits, String[] numToChar) {
            if(digits.compareTo("") == 0){
                return new LinkedList<>();
            }
            
            List<String> result = new LinkedList<>();
            List<String> nextResult = letterCombinations(digits.substring(1), numToChar);
            String mapping = numToChar[Character.getNumericValue(digits.charAt(0))];
            
            for(int i = 0; i<mapping.length(); i++) {
                if(nextResult.size() == 0) {
                    result.add(String.valueOf(mapping.charAt(i)));
                }
                else {
                    for(int k = 0; k<nextResult.size(); k++) {
                        result.add(mapping.charAt(i)+nextResult.get(k));
                    } 
                }
            }
            return result;
        }

Log in to reply
 

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