Java solution using BackTrack


  • 1
    A

    public class Solution {

    List<String> list;
    
    public List<String> letterCombinations(String digits) {
        
        list=new ArrayList<String>();
        if(digits.length()==0) return list;
        
        backTrack(digits,"",0);
        return list;
    }
    
    void backTrack(String digits,String letter,int index){
        
        if(index>=digits.length()){
            list.add(new StringBuilder(letter).toString());
            return;
        }
        
        //Multiple of letters
        int num = digits.charAt(index) - '2';
        
        int end;
        if(num==5||num==7) end=4;
        else end=3;
        
        //Set letters
        for(int i=0;i<end;i++){
            char c;
            if(num<5) c=(char)('a'+(num*3+i));
            else if(num==5) c=(char)('p'+i);
            else if(num==6) c=(char)('t'+i);
            else c=(char)('w'+i);
            
            String newLetter = new StringBuilder(letter).toString();
            backTrack(digits,letter+c,index+1);
        }
    }
    

    }


Log in to reply
 

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