Java Straightforward Backtracking Solution


  • 0
    X

    public class Solution {
    public List<String> letterCombinations(String digits) {
    List<String> res = new ArrayList<>();

        if(digits==null || digits.length()==0) return res;
        helper(digits,res,new StringBuilder(),0);
        return res;
    }
    
    private void helper(String digits,List<String> res, StringBuilder curr,int i){
        if(i==digits.length()){
            res.add(curr.toString());
            return;
        }
        int letterNo=3;
        int addNo=0;
        if(digits.charAt(i)=='9'){
            letterNo=4;
            addNo=1;
        }
        else if(digits.charAt(i)=='7') letterNo = 4;
        else if(digits.charAt(i)=='8') addNo=1;
        
        for(int j=0;j<letterNo;j++){
            char currChar = (char)((digits.charAt(i)-'2')*3+addNo+j+'a');
            helper(digits,res,curr.append(currChar),i+1);
            curr.deleteCharAt(curr.length()-1);
        }
    }
    

    }


Log in to reply
 

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