The fastest 1ms Java solution with clear code


  • 0
    A

    The fastest java solution still be the backtracking which is the following:

    public class Solution {
        public List<String> letterCombinations(String digits) {
            List<String> res = new LinkedList<>();
            StringBuilder sb = new StringBuilder();
            String[] mapping = {"0","1","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
            if(digits==null || digits.length()==0)
                return res;
            doCombin(digits,mapping, 0, sb, res);
            return res;
        }
        
        void doCombin(String digits, String[] mapping, int cur, StringBuilder sb, List<String> res){
            if(sb.length() == digits.length()){
                res.add(sb.toString());
                return;
            }
            for(char c : mapping[digits.charAt(cur)-'0'].toCharArray()){
                sb.append(c);
                doCombin(digits,mapping,cur+1,sb,res);
                sb.deleteCharAt(cur);
            }
        }
    }

Log in to reply
 

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