我正在尝试生成 vector 的所有排列来训练回溯技术,但我的代码不适用于所有 vector (适用于 vector 大小)
我的代码:
#include <bits/stdc++.h>
using namespace std;
void permutations(int s,vector<int> v){
if(s>=v.size())
return;
if( v.size()==0)
cout<<endl;
cout<<v[s]<<" ";
vector<int> k = v;
k.erase(k.begin()+s);
for(int i =0;i<k.size();i++)
return permutations(i,k);
}
int main(int argc, char const *argv[])
{
vector<int> v = {1,2,3};
for(int i =0;i<v.size();i++){
permutations(i,v);
cout<<endl;
}
return 0;
}
我认为是因为当我的递归函数 find return 时,它们破坏了 for 但也许我错了,有人可以告诉我问题是什么以及我该如何纠正它。
最佳答案
简单的方法是使用标准算法:std::next_permutation
void print(const std::vector<int>& v)
{
for (int e : v) {
std::cout << " " << e;
}
std::cout << std::endl;
}
int main()
{
std::vector<int> v = {1,2,3};
// vector should be sorted at the beginning.
do {
print(v);
} while (std::next_permutation(v.begin(), v.end()));
}
关于c++ - 所有排列 C++ 与 vector <int> 和回溯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32678349/