Simple recursive Java solution


  • 0
    A
    public class Solution {
        public List<String> letterCombinations(String digits) {
            if (digits == null || digits.length() == 0) {
                return new ArrayList<String>(); 
            }
            
            String[] map = new String[]{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};  
            List result = new ArrayList<String>(); 
            
            helper(digits, map, "", result); 
            
            return result; 
        }
        
        private void helper(String digits, String[] map, String str, List<String> result) {
            if (digits.length() == 0) {
                result.add(str); 
            } else {
                int num = Integer.parseInt(digits.substring(0, 1)); 
                String vals = map[num]; 
                for (int i = 0; i < vals.length(); i++) { 
                    helper(digits.substring(1), map, str + vals.substring(i, i+1), result);
                }
            }
        }
    }
    

Log in to reply
 

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