Solution use dfs and backtracking


  • 0
    R

    class Solution {
    public List<String> letterCombinations(String digits) {
    // dfs classical algorithm, need backtracking
    // corner case
    List<String> res = new ArrayList<>();
    if (digits == null || digits.length() == 0) return res;

        String[] sdig = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        // go dfs template
        StringBuilder sb = new StringBuilder();
        dfs(res, digits, sdig, 0, sb);
        
        return res;
    }
    public void dfs(List<String> res, String digits, String[] sdig, int start, StringBuilder sb) {
        // exit condition
        if (start == digits.length()) {
            res.add(sb.toString());
            return;
        }
        int index = digits.charAt(start)-'0';
        if (sdig[index].length() == 0) {
            dfs(res, digits, sdig, start+1, sb);
        } else {
            // dfs main dealing processing
            for (int i = 0; i < sdig[index].length(); i++) {
                sb.append(sdig[index].charAt(i));
                dfs(res, digits, sdig, start+1, sb);
                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.