跳到主要内容

深度优先搜索(DFS)

参考资料

例题

洛谷 P1157 组合的输出

排列与组合是常用的数学方法,其中组合就是从 nn 个元素中抽出 rr 个元素(不分顺序且 rnr \le n),我们可以简单地将 nn 个元素理解为自然数 1,2,,n1,2,\dots,n,从中任取 rr 个数。

现要求你输出所有组合。

代码(1)
#include <bits/stdc++.h>
using namespace std;

const int N=25;
int a[N];
void dfs(int u,int n,int r)
{
if(u>r)
{
for(int i=1;i<=r;i++)
{
cout<<setw(3)<<a[i];
}
cout<<'\n';
return;
}
for(int i=a[u-1]+1;i<=n;i++)
{
a[u]=i;
dfs(u+1,n,r);
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n,r;
cin>>n>>r;
dfs(1,n,r);
return 0;
}

洛谷 P1706 全排列问题

按照字典序输出自然数 11nn 所有不重复的排列,即 nn 的全排列。(1n91\le n\le9

代码(1)
#include <bits/stdc++.h>
using namespace std;

const int N=20;
int a[N];
bool vis[N];
void dfs(int u,int n)
{
if(u>n)
{
for(int i=1;i<=n;i++)
{
cout<<setw(5)<<a[i];
}
cout<<'\n';
return;
}
for(int i=1;i<=n;i++)
{
if(vis[i])continue;
a[u]=i;
vis[i]=1;
dfs(u+1,n);
vis[i]=0;
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin>>n;
dfs(1,n);
return 0;
}