backtracking Java version. Use the backtracking templated


  • 0
    Z

    Uses the backtracking template:
    https://discuss.leetcode.com/topic/46162/a-general-approach-to-backtracking-questions-in-java-subsets-permutations-combination-sum-palindrome-partioning

    public class Solution {
        public ArrayList<String> letterCombinations(String digits) {
            ArrayList<String> list = new ArrayList<String>();
    
            if (digits == null || digits.equals("")) {
                return list;
            }
    
            Map<Character, char[]> map = new HashMap<Character, char[]>();
            map.put('0', new char[] {});
            map.put('1', new char[] {});
            map.put('2', new char[] { 'a', 'b', 'c' });
            map.put('3', new char[] { 'd', 'e', 'f' });
            map.put('4', new char[] { 'g', 'h', 'i' });
            map.put('5', new char[] { 'j', 'k', 'l' });
            map.put('6', new char[] { 'm', 'n', 'o' });
            map.put('7', new char[] { 'p', 'q', 'r', 's' });
            map.put('8', new char[] { 't', 'u', 'v'});
            map.put('9', new char[] { 'w', 'x', 'y', 'z' });
    
            backtrack(list, new StringBuilder(), map, digits);
    
            return list;
        }
    
        private void backtrack(ArrayList<String> result, StringBuilder sb, Map<Character, char[]> map, String digits) {
            if (sb.length() == digits.length()) {
                result.add(sb.toString());
            } else {
                for (char c : map.get(digits.charAt(sb.length()))) {
                    sb.append(c);
                    backtrack(result,sb,map, digits);
                    sb.deleteCharAt(sb.length() - 1);
                }
            } 
        }
    }
    

Log in to reply
 

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