gpt4 book ai didi

c++ - 这段代码的递归形式是什么?

转载 作者:行者123 更新时间:2023-11-28 06:38:45 25 4
gpt4 key购买 nike

我试图在 vector b 中定位 vector a。所以这就像如果 vector a 在 vector b 中则返回 true 否则返回 false。 vector a 应该像 {1,2,3},b 应该像 {4,1,2,3,5,5,7}。这段代码的输出是 true 1 和 false 0。所以我的问题是我不希望 1 和 0 出现在输出中。我也想以递归形式编写这段代码,所以有人可以帮我解决这个问题吗?

    bool x(vector<int>& a, vector<int>  b)
{
vector<int> index ( b.size(),0 );
int counter = 0;

if ( a.size() <= b.size() ) {

for ( int i = 0; i < a.size(); i++ ) {
for ( int j = 0; j < b.size(); j++ ) {
if ( a[i]== b[j]) {
index[j] = 1;
}
}
}

for ( int i = 0; i < index.size(); i++ ) {
if ( index[i] == 1 ) {
for ( int j = i; j < index.size(); j++ ) {
if ( index[j] == 1 ) {
counter++;
}
}
if(counter == a.size()){
cout<<"true"<<endl;
return true;
break;
}
else{
counter = 0;
cout<<"false"<<endl;
return false;
// continue;
}

}
}
}
return 0;
}

最佳答案

如果您只是不喜欢输出:true 1 和 false 0。最简单的解决方法是:
if(x(a, b)){
cout<<"true"<<endl;
} else {
cout<<"false"<<endl;
}

但是,在您尝试将算法转换为递归算法之前,我担心您的算法是错误的。尝试这个:
vector<int> a;
vector<int> b;
a.push_back(1);
a.push_back(2);
a.push_back(3);
b.push_back(1);
b.push_back(1);
b.push_back(1);
cout<<x(a,b)<<endl;

你会得到 true,正确答案是 false。

检查你的算法!

关于c++ - 这段代码的递归形式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26333294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com