OVSolitario-io

导航

lambda自递归

auto dfs =:定义匿名函数并赋值给 dfs;
[&]:捕获外部作用域变量以引用方式访问;
auto &self:自传递实现lambda 内部递归;
-> void:显式指定返回类型(函数类型);

auto dfs = [&] (auto &self,  参数) -> 返回类型 {
	self(self, 参数操作);//用self递归
};
//例如:
auto dfs = [&] (auto &self, int u, int p) -> void { };

注意结束括号要有;

举例:

点击查看代码
int main() {
    cin >> n;
    auto dfs = [&](auto &self, int u) - void{
        if(u == n) {
            for(int i = 0; i < n; ++ i) cout << q[i] << ' ';
            cout << endl;
            return ;
        }  
        for(int i = 1; i <= n; ++ i) {
            if(!st[i]) {
                q[u] = i;
                st[i] = 1;
                self(self, u + 1);//self递归
                st[i] = 0;
            }
        }
    };
    dfs(dfs, 0);
    return 0;
}
对于此code中[&]捕获main函数中all局部变量(全局不用捕获直接用)

posted on 2025-10-09 08:57  TBeauty  阅读(7)  评论(0)    收藏  举报