深搜模板

function dfsTemplate(root) {
    //存储最终结果
    let res;
    //初始化当前结果
    let start;
    //构造递归函数dfs,通常参数为当前节点和当前结果
    let dfs = function (node, currentResult) {
        //终止条件返回判断
        if (node == null) {
            return;
        }
        //更新当前结果currentResult

        //若到达末尾叶子结点,进行最优结果更新
        if (node.left == null && node.right == null) {
            //update res
        }
        //左右子树递归
        dfs(node.left, currentResult);
        dfs(node.right, currentResult);
    }
    dfs(root, start);
    return res;
}

全排列

#include<bits/stdc++.h>
using namespace std;
int n;
bool vis[50];
int a[50];
void dfs(int step)//层数
{
	if(step==n+1)
	{
		for(int i=1;i<=n;i++)
			cout << setw(5) << a[i];
		cout << endl;
		return;
	}
	if(step<=n)
	{
		for(int i=1;i<=n;i++)
		{
			if(vis[i]==0)
			{
				vis[i]=1;
				a[step]=i;
				dfs(step+1);
				vis[i]=0;
			}
		}
	}
}

int main()
{
	cin >> n;
	dfs(1);
	return 0;
}

 

posted @ 2022-05-29 16:25  风乐  阅读(93)  评论(0编辑  收藏  举报