My easy understanding recursion solution in Java


  • 0
    • How to handle 0 and 1?
    • From out output of the OJ, return [] if contians 0 or 1.
    • Use an array to store the strings of each number.
    • Choose every char in each string of the array to construct a string recursively, and add this string to the result.

    Attached is the AC code (1ms) :

    public class Solution {
      List<String> ret, input;
      public List<String> letterCombinations(String digits) {
        ret = new ArrayList<String>();
        input = new ArrayList<String>();
        if(digits==null || digits.length()==0 || digits.contains("0") || digits.contains("1")) return ret;
        String[] dict = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz", ""};
        String stmp = new String();
        for(int i=0;i<digits.length();i++)
          input.add(dict[digits.charAt(i)-'0']);
        func(0, stmp);
        return ret;
      }
      private void func(int level, String stmp){
        if(level==input.size()-1)
          for(int i=0;i<input.get(level).length();i++)
            ret.add(stmp+input.get(level).charAt(i));
        else
          for(int i=0;i<input.get(level).length();i++)
            func(level+1, stmp+input.get(level).charAt(i));
      }
    }

Log in to reply
 

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