Backtracking algorithm: introduction to backtracking, the number of combinations

The number of combinations question
Insert picture description here
ideas:
Insert picture description here

The classic problem of backtracking algorithm, backtracking solves the problem of n-level for loop nesting. If the for loop is a horizontal traversal, then backtracking is a vertical traversal. The number of combinations is abstracted as the depth of the tree, and n is the width of the tree. k is the depth of the tree, and every time we search for the leaf nodes on the tree, we find the result.

General template for backtracking:

void backtracking(参数) {
    
    
    if (终止条件) {
    
    
        存放结果;
        return;
    }

    for (选择:本层集合中元素(树中节点孩子的数量就是集合的大小)) {
    
    
        处理节点;
        backtracking(路径,选择列表); // 递归
        回溯,撤销处理结果
    }
}

Code:

class Solution {
    
    
public:
    vector<vector<int>> result;//所有路径
    vector<int> path;//当前路径
    vector<vector<int>> combine(int n, int k) {
    
    
        back(n, k, 1);
        return result;
    }
    void back(int n, int k,int index)
    {
    
    
        if (path.size() == k)//结束条件
        {
    
    
             return result.push_back(path);
        }
        for (int i=index; i <= n; i++)
        {
    
    
            path.push_back(i);//处理结点
            back(n, k, i+1);//递归
            path.pop_back();//回溯的关键,退回元素,撤销上一次的操作
        }
    }
};

Guess you like

Origin blog.csdn.net/cckluv/article/details/111589926