排列
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<iomanip>
int vis[25],ans[25];
int n;
using namespace std;
void dfs(int dep)
{
if(dep==n+1)
{
for(int i=1;i<=n;i++)
cout<<setw(5)<<ans[i];
cout<<endl;
return;
}
for(int i=1;i<=n;i++)
{
if(!vis[i])
{
vis[i]=1;
ans[dep]=i;
dfs(dep+1);
vis[i]=0;
}
}
}
int main()
{
cin>>n;
dfs(1);
}
组合
#include<cstdio>
#include<iostream>
#include<iomanip>
using namespace std;
int n,r;
int ans[26];
void dfs(int dep)
{
if(dep==r+1)
{
for(int i=1;i<=r;i++)
cout<<setw(3)<<ans[i];
cout<<endl;
return;
}
for(int i=ans[dep-1]+1;i<=n;i++)
{
ans[dep]=i;
dfs(dep+1);
}
}
int main()
{
cin>>n>>r;
dfs(1);
}
标签:std,25,int,dfs,dep,算法,搜索,回溯,include
From: https://blog.csdn.net/2302_79599802/article/details/136760892