Share my backtracking method in Java, easy to understand.


  • 0
    Z
    class Solution {
        private final String[] dict = new String[]{" ", "", "abc", "def", "ghi", "jkl", "mno", "qprs", "tuv", "wxyz"};
        public List<String> letterCombinations(String digits) {
            List<String> res = new ArrayList<>();
            if (digits == null || digits.length() == 0) return res;
            backtrack(res, new StringBuilder(), digits, 0);
            return res;
        }
        private void backtrack(List<String> list, StringBuilder temp, String digits, int pos) {
            if (pos == digits.length()) {
                list.add(temp.toString());
                return;
            }
            int index = digits.charAt(pos) - '0';
            for (int i = 0; i < dict[index].length(); i++) {
                temp.append(dict[index].charAt(i));
                backtrack(list, temp, digits, pos + 1);
                temp.deleteCharAt(temp.length() - 1);
            }
        }
    }
    

Log in to reply
 

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