glass_goldfish @ 2024-06-15 16:07:41
#include<bits/stdc++.h>
using namespace std;
int n,m,used[11],a[11];
void dfs(int p)
{
if(p==m){
cout<<a[1];
for(int i=2;i<=m;i++)
cout<<" "<<a[i];
cout<<"\n";
return;
}
for(int i=1;i<=n;i++){
if(used[i])continue;
used[i]=1;
p++;
a[p]=i;
dfs(p);
used[i]=0;
}
}
int main()
{
cin>>n>>m;
dfs(0);
return 0;
}
by glass_goldfish @ 2024-06-15 16:08:33
输入3 2
输出1 2\n1 2
by _lfggy__liangfeng__ @ 2024-06-15 16:14:56
@liulijinyu used不应该定义bool吗
by _lfggy__liangfeng__ @ 2024-06-15 16:17:47
@liulijinyu 少个"p--"!你加了没减去!
by _lfggy__liangfeng__ @ 2024-06-15 16:18:52
@liulijinyu
#include<bits/stdc++.h>
using namespace std;
int n,m,a[11];
bool used[11];
void dfs(int p)
{
if(p==m)
{
for(int i=1;i<=m;i++)
cout<<a[i]<<" ";
cout<<endl;
return;
}
for(int i=1;i<=n;i++)
{
if(used[i]) continue;
used[i]=1,p++;
a[p]=i,dfs(p);
used[i]=0,p--;
}
}
int main()
{
cin>>n>>m;
dfs(0);
return 0;
}
by glass_goldfish @ 2024-06-15 16:19:35
@_lfggyliangfeng AC了,感蟹!!!!关你了
by glass_goldfish @ 2024-06-15 16:20:51
@_lfggyliangfeng 这是我的代码
#include<bits/stdc++.h>
using namespace std;
int n,m,a[11];
bool used[11];
void dfs(int p)
{
if(p==m){
cout<<a[1];
for(int i=2;i<=m;i++)
cout<<" "<<a[i];
cout<<"\n";
return;
}
for(int i=1;i<=n;i++){
if(used[i])continue;
used[i]=1;
p++;
a[p]=i;
p--;
dfs(p+1);
used[i]=0;
}
}
int main()
{
cin>>n>>m;
dfs(0);
return 0;
}
by _lfggy__liangfeng__ @ 2024-06-15 16:22:38
@liulijinyu 其实used写int也行,但是从逻辑上bool更好
以后写搜索的时候要注意搜完了要恢复,不然p就会永远变大
by glass_goldfish @ 2024-06-15 16:24:06
@_lfggyliangfeng ok