Code Caprice Algorithm Training Camp Day 24 | Backtracking Algorithm Theoretical Basis, 77. Combination

Table of contents

Theoretical basis of backtracking algorithm

77. Combination


Theoretical basis of backtracking algorithm

In fact, when explaining the binary tree, I introduced backtracking to you. This time the backtracking algorithm is officially launched. You can watch the video first to have an overall understanding of the backtracking algorithm.

Topic link/article explanation: code caprice

Video explanation: Take you to learn the backtracking algorithm (theoretical articles) | Intensive lecture on the backtracking method! _哔哩哔哩_bilibili


77. Combination

Facing the code template given in The Theoretical Basis of Backtracking Algorithm, to do the combination problem of this question, everyone will find the routine of writing backtracking algorithm. In the process of backtracking algorithm to solve practical problems, you will have various questions. Watch the video introduction first, which can basically solve your doubts. The pruning operation in this question is the key point for everyone to understand, because many problems solved by backtracking algorithms in the future are all pruning routines.

Topic link/article explanation: code caprice

Video explanation: Take you to learn the backtracking algorithm-combination problem (corresponding to stress button topic: 77. Combination) | Intensive lecture on backtracking method! _哔哩哔哩_bilibili

Pruning operation: Take you to learn the backtracking algorithm-pruning operation for combination problems (corresponding to stress buckle topic: 77. Combination) | Intensive lecture on backtracking method! _哔哩哔哩_bilibilis

Problem solution idea:
the first time to write a backtracking algorithm, the pits inside have begun to be insufficient! ! ! A lot of details are worth noting. Here you can understand it not only by listening to Kage’s video, but you need to debug step by step to understand the backtracking algorithm in it.

class Solution {

    LinkedList<Integer> path = new LinkedList<>();
    List<List<Integer>> result = new ArrayList<>();

    public List<List<Integer>> combine(int n, int k) {
        backtracking(n, k, 1);
        return result;

    }

    public void backtracking(int n, int k, int start){
        if(path.size() == k){
            result.add(new LinkedList<>(path)); //将 path 集合中的所有元素添加到新的集合中,因为path集合中的元素一直变化的,需要对符合条件的结果path复制一份到新的集合中
            return;
        }
        for(int i = start; i <= n; i++){
            path.add(i);
            backtracking(n, k, i + 1);
            path.removeLast(); //LinkedList集合所有的操作和双端队列差不多,能实现移除尾部元素操作,从而达到回溯目的,这里如果使用arraylist就不能实现删除尾部元素操作了!!!
        }
    }
}

Guess you like

Origin blog.csdn.net/tore007/article/details/130659950