A simple Java recursive solution


  • 0
    L
        private static final Map<Character,String> map = new HashMap<>();
        static {
            map.put('1',"1");
            map.put('2',"abc");
            map.put('3',"def");
            map.put('4',"ghi");
            map.put('5',"jkl");
            map.put('6',"mno");
            map.put('7',"pqrs");
            map.put('8',"tuv");
            map.put('9',"wxyz");
        }
        public List<String> letterCombinations(String digits) {
            if(digits.isEmpty()) {
                return Collections.emptyList();
            }
            return helper(digits,0,"");        
        }
        
        private List<String> helper(String digits, int i, String s) {
            //exit condition.
            if(s.length()==digits.length()) {
                return Arrays.asList(s);
            }
            
            List<String> list = new ArrayList<>();
            char c1 = digits.charAt(i);
            for(char c2 : map.get(c1).toCharArray()) {
                list.addAll(helper(digits,i+1,s+c2));
            }
          
          return list;  
        }
    

Log in to reply
 

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