#include <bits/stdc++.h>
#define endl '\n'
typedef long long ll;
using namespace std;
const int N=10000;
int a[N]={0},b[N]={0}; //原数组和临时存放排序的数组
int c[N]={0}; //用来标记第i个元素有没有用
int n; //输入的元素个数
void dfs(int k){
if(k==n){
for(int i=0;i<n;i++){
cout<<b[i]<<" ";
}
cout<<endl;
}
else{
for(int i=0;i<n;i++){
if(c[i]==0){
b[k]=a[i];
c[i]=1;
dfs(k+1);
c[i]=0;
}
}
}
}
void slove(){
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
}
dfs(0);
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t=1;
//cin>>t;
while(t)
slove();
return 0;
}
C++全排列,运用dfs算法,代码不报错,但是运行答案不对
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
4条回答 默认 最新
关注让【宝码香车】来帮你解答,本回答参考DeepSeek编写,并整理提供,如果还有疑问可以点击头像关注私信或评论。
如果答案让您满意,请采纳、关注,非常感谢!
你的代码整体思路是正确的,使用了深度优先搜索(DFS)来生成全排列。不过,代码中存在一个小问题,导致程序无法正常结束。具体来说,
while(t)这个循环条件会导致程序无限循环,因为t的值始终为1,没有在循环中被修改。问题分析:
- 无限循环问题:
while(t)中的t始终为1,导致程序无法退出循环。 - 输入问题:如果输入的元素个数
n为0,程序不会输出任何结果,但也不会报错。
解决方案:
- 修复无限循环问题:你可以通过修改
while(t)的条件来避免无限循环。例如,你可以将t设置为0或者在slove()函数中处理输入后退出循环。 - 输入处理:确保输入的元素个数
n大于0,否则程序不会输出任何结果。
修改后的代码:
#include <bits/stdc++.h> #define endl '\n' typedef long long ll; using namespace std; const int N=10000; int a[N]={0},b[N]={0}; //原数组和临时存放排序的数组 int c[N]={0}; //用来标记第i个元素有没有用 int n; //输入的元素个数 void dfs(int k){ if(k==n){ for(int i=0;i<n;i++){ cout<<b[i]<<" "; } cout<<endl; } else{ for(int i=0;i<n;i++){ if(c[i]==0){ b[k]=a[i]; c[i]=1; dfs(k+1); c[i]=0; } } } } void slove(){ cin>>n; for(int i=0;i<n;i++){ cin>>a[i]; } dfs(0); } int main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t=1; //cin>>t; while(t--){ slove(); } return 0; }解释:
- **
while(t--)**:将while(t)改为while(t--),这样t会在每次循环后递减,最终变为0,从而退出循环。 - 输入处理:确保输入的元素个数
n大于0,否则程序不会输出任何结果。
测试:
你可以输入以下数据进行测试:
3 1 2 3输出应该为:
1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1这样修改后,程序应该能够正确输出全排列,并且不会陷入无限循环。
本回答被题主选为最佳回答 , 对您是否有帮助呢?评论 打赏 举报解决 1无用- 无限循环问题: