4. Backtracking

Template

void backtrack(int[] candidates, int index, other params, List<Integer> path, List<List<Integer>> result) {
    if (satisfied condition) {
        results.add(new ArrayList<>(path));
    }
    
    for (option in options) {
        //Skip not satified
        if (need filter) {
            continue;
        }
        path.add(option);
        backtrack(candidates, newIndex, path, results);
        path.remove(path.size() - 1);
    }
}

Typic problems

  • Permute problem, the time complexity of permute problems is (n! - factorial of n)

  • Combination & Subset, where order doesn't matter,

    • the time complexity subset is O(2^n), because for each element, we have two choices: either include it in the subset or exclude it. Since there are n elements, we have 2^n possible combinations of including or excluding each element.

    • For combination of K out of n element, the time complexity is (n!/(k!*(n−k)!)​), This is because, at each step, we have n choices to consider for the next element, but we only need to consider k elements. Hence, the number of recursive calls made is proportional to the number of combinations

Combination sum

5. DFS

Last updated