Top-down recursion in Java


  • 0
    class Solution {
      private String[] keyboard = { "", "", "abc", "edf", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
    
      public List<String> letterCombinations(String digits) {
        List<String> list = new ArrayList<>();
        if (digits == null || digits.isEmpty())
          return list;
    
        int i = digits.charAt(digits.length() - 1) - '0';
        char[] cs = keyboard[i].toCharArray();
    
        if (digits.length() == 1) {
          for (char c : cs)
            list.add(String.valueOf(c));
        } else {
          String sub = digits.substring(0, digits.length() - 1);
          List<String> temp = letterCombinations(sub);
          for (char c : cs) {
            for (String s : temp) {
              list.add(s + c);
            }
          }
        }
        return list;
      }
    }
    

Log in to reply
 

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