Recursive java solution beating 50%


  • 0
    F

    public class Solution {
    public List<String> letterCombinations(String digits) {
    List<String> list=new ArrayList<String>();
    String[] mapping = new String[] {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    String temp="";
    read(digits,mapping,list,temp);
    return list;
    }

    public void read(String digits,String[] mapping,List<String> list,String temp){
         if(digits.length()==0)
          return;
         
         if(Character.getNumericValue(digits.charAt(0))==0||Character.getNumericValue(digits.charAt(0))==1)
           read(digits.substring(1),mapping,list,temp);
           
           for(int i=0;i<mapping[Character.getNumericValue(digits.charAt(0))].length();i++){
               temp=temp+mapping[Character.getNumericValue(digits.charAt(0))].charAt(i);
               if(digits.length()==1)
               list.add(temp);
               read(digits.substring(1),mapping,list,temp);
               temp=temp.substring(0,temp.length()-1);
        } 
    }
    

    }


Log in to reply
 

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