Short and Elegant recursive solution with no extra method


  • 0
    O
    static String[] strs = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    public List<String> letterCombinations(String digits) {
        List<String> ret = new ArrayList<>();
        if (digits.length() == 0) 
            return ret;
        if (digits.length() == 1) {
            for (char c : strs[digits.charAt(0)-'0'].toCharArray()) {
                ret.add(c + "");
            }
            return ret;
        }
        for (char c : strs[digits.charAt(0)-'0'].toCharArray()) {
            for (String s : letterCombinations(digits.substring(1))) {
                ret.add(c + s);
            }
        }
        return ret;
    }

Log in to reply
 

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