一.递归实现指数型枚举
#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define endl '\n'
typedef long long LL;
typedef pair<int,int> PII;
bool st[20];
int n;
void dfs(int u)
{
if(u >= n+1)
{
for(int i=1;i <= n;i++) if(st[i]) cout<<i<<' ';
cout<<endl;
return ;
}
st[u]=true;
dfs(u+1);
st[u]=false;
dfs(u+1);
}
int main()
{
IOS;
cin>>n;
dfs(1);
return 0;
}
它的枚举策略是枚举每个数字(或者方案)要还是不要。
二.递归实现组合类型枚举
#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define endl '\n'
typedef long long LL;
typedef pair<int,int> PII;
int path[10];
int n;
void dfs(int u,int last)
{
if(u >= 3)
{
for(int i=0;i < 3;i++) cout<<path[i]<<' ';
cout<<endl;
}
for(int i=last;i <= n;i++)
{
path[u]=i;
dfs(u+1,i+1);
}
}
int main()
{
IOS;
cin>>n;
dfs(0,1);
return 0;
}
枚举位置,然后注意为了防止重复枚举,每次递归要记下上个位置放的数。
三.递归实现全排列型枚举
#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define endl '\n'
typedef long long LL;
typedef pair<int,int> PII;
const int N=20;
bool st[N];
int path[N];
int n;
void dfs(int u)
{
if(u >= n)
{
for(int i=0;i < n;i++) cout<<path[i]<<' ';
cout<<endl;
}
for(int i=1;i <= n;i++)
{
if(!st[i])
{
path[u]=i;
st[i]=true;
dfs(u+1);
st[i]=false;
}
}
}
int main()
{
IOS;
cin>>n;
dfs(0);
return 0;
}
也是枚举位置,但是注意它的数字的摆放不和组合型一样,其考虑了顺序。只要保证每个数字不会重复拜访即可。