Simple 1ms java solution with backtracking


  • 1
    C
    public List<String> letterCombinations(String digits) {
            if(digits.length()==0) return new ArrayList<String>();
            ArrayList<String> result = new ArrayList<String>();
            String[] numToLetter = new String[]{"","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
            String curr = "";
            helper(0,digits,curr,result,numToLetter);
            return result;
        }
        private void helper(int pos, String digits, String curr, ArrayList<String> result, String[] numToLetter){
            if(curr.length()==digits.length()) result.add(new String(curr));
            else{
                for(int j=0;j<numToLetter[digits.charAt(pos)-'1'].length();j++){
                    curr += "" + numToLetter[digits.charAt(pos)-'1'].charAt(j);
                    helper(pos+1,digits,curr,result,numToLetter);
                    curr = curr.substring(0,curr.length()-1);
                }
            }
        }
    

Log in to reply
 

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