Accepted Solution in Java (Recursive)


  • 0
    H
    String[] mappings = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    public List<String> letterCombinations(String digits) {
        List<String> result = new ArrayList<>();
        if (digits.length() == 0) {
            return result;
        }
        StringBuilder temp = new StringBuilder();
        combinations(result, temp, digits, 0);
        return result;
    }
    
    public void combinations(List<String> res, StringBuilder temp, String digits, int level) {
        if (level == digits.length()) {
            res.add(temp.toString());
            return;
        }
    
        int index = digits.charAt(level) - '0';
        for (int i = 0; i < mappings[index].length(); i++) {
            temp.append(mappings[index].charAt(i));
            combinations(res, temp, digits, level + 1);
            temp.setLength(temp.length() - 1);
        }
    }

Log in to reply
 

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