DFS + Backtracking

When to use Backtracking

  • Basically, going back to the previous level and check the unvisited neighboring nodes. 顾名思义,回溯。即回到上一层查未查过的邻节点。

  • Brute force solution, usually to list all the possibilities. 暴力解法,穷举所有可能性

Notes 注意一些坑

  • 对于全局变量,如visited[][],需在访问下一层之前置true,并在返回上一层之前置false

  • what to return when meet the termination conditions,如越界无限循环(访问已访问过的节点)触底

经典题目

17 Letter Combinations of a Phone Number 39 Combination Sum 351 Android Unlock Patterns

String[] dict = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public List<String> letterCombinations(String digits) {
    List<String> res = new ArrayList<>();
    if (digits == null || digits.length() == 0) return res;
    StringBuilder cur = new StringBuilder();
    helper(digits, 0, cur, res);
    return res;
}
private void helper(String digits, int index, StringBuilder sb, List<String> res) {
    // base case
    if (index == digits.length()) {
        res.add(sb.toString());
        return;
    }
    String chars = dict[digits.charAt(index) - '0'];
    for (int i = 0; i < chars.length(); i++) {
        sb.append(chars.charAt(i));
        helper(digits, index + 1, sb, res);
        sb.deleteCharAt(sb.length() - 1);
    }
}

247 Strobogrammatic Number II 248 Strobogrammatic Number III

301 Remove Invalid Parentheses

Last updated