求救! 誰可以跟我講我遞迴哪裡出問題? 它一直無窮迴圈......
# include <bits/stdc++.h>
using namespace std;
int n,i;
vector<int> ans;
vector<bool> vb(8,false);
void dfs(int x){
ans.push_back(x);
vb[x-1] = true;
if (count(vb.begin(),vb.end(),false) == 8-n){
for (int j=0; j<n; j++) cout << ans[j];
cout << '\n';
ans = {i};
for (int k=0; k<8; k++) vb[k] = false;
vb[n-1] = true;
}
else{
for (int k=n; k>=1; k--){
if (vb[k-1] == true) continue;
else dfs(k);
}
}
return;
}
int main()
{
while (cin >> n){
for (i=n; i>=1; i--){
dfs(i);
for (int j=0; j<8; j++) vb[j]=false;
}
}
return 0;
}
example
input
3
output
321
312
312
.
.
.
求救! 誰可以跟我講我遞迴哪裡出問題? 它一直無窮迴圈......
# include
using namespace std;int n,i;
vector ans;
vector vb(8,false);
void dfs(int x){
ans.push_back(x);
vb[x-1] = true;
if (count(vb.begin(),vb.end(),false) == 8-n){
for (int j=0; j cout << '\n';
ans = {i};
for (int k=0; k<8; k++) vb[k] = false;
vb[n-1] = true;
}
else{
for (int k=n; k>=1; k--){
if (vb[k-1] == true) continue;
else dfs(k);
}
}
return;
}int main()
{
while (cin >> n){
for (i=n; i>=1; i--){
dfs(i);
for (int j=0; j<8; j++) vb[j]=false;
}
}return 0;
}
example
input
3
output
321
312
312
.
.
.
因為你的vb和ans在遞迴中會整個被改掉,我覺得vb用不到可以刪掉,而ans只要在離開dfs()函式時pop_back就好,而不是在輸出時整個刪掉