C++ 没有递归的置换?
我试图使用for循环来替换我通常使用的递归,但我发现这比我想象的要难。有人能告诉我怎么做吗?谢谢 例如,给定一个向量2,1,3。应该有六种排列:C++ 没有递归的置换?,c++,permutation,non-recursive,C++,Permutation,Non Recursive,我试图使用for循环来替换我通常使用的递归,但我发现这比我想象的要难。有人能告诉我怎么做吗?谢谢 例如,给定一个向量2,1,3。应该有六种排列: 1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1 向量在下面 vector<int> simple; simple.push_back(2); simple.push_back(1); simple.push_back(3); 向量简单; 简单。推回(2); 简单。推回(1); 简单。推回(3); 编辑:将顺序从
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
向量在下面
vector<int> simple;
simple.push_back(2);
simple.push_back(1);
simple.push_back(3);
向量简单;
简单。推回(2);
简单。推回(1);
简单。推回(3);
编辑:将顺序从1 2 3更改为随机顺序2 1 3我想您正在寻找: 这是一本书
请注意,如果向量的大小在编译时已知,就像您的示例中的情况一样,您可以使用而不是
std::vector
,如所示。您尝试了什么吗?使用。如果您想使用boost:@PeterWood,那么下一次排列似乎需要输入有序?@Arch1tect是,要以最简单的方式获得所有排列,首先需要对其进行排序。似乎下一个排列需要输入有序?@Arch1tect:有点,你是对的。如果您希望在next\u permutation
返回false
之前找到所有置换,那么是的。我仅使用1 2 3作为示例,向量不必按顺序排列。你知道怎么解决这个问题吗?无论如何,谢谢。:@Arch1tect:我更新了我的答案factorial
,如果向量中有重复项,我的答案就不是你想要的了。
#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
std::vector<int> simple{1, 2, 3};
do
{
for (auto e : simple) { std::cout << e << " "; }
std::cout << std::endl;
}
while (next_permutation(simple.begin(), simple.end()));
}
#include <iostream>
#include <algorithm>
#include <vector>
constexpr int factorial(int i)
{
return i == 0 ? 1 : i * factorial(i-1);
}
int main()
{
std::vector<int> simple{3, 1, 2};
for (int i = 0; i < factorial(simple.size()); i++)
{
std::next_permutation(simple.begin(), simple.end());
for (auto e : simple) { std::cout << e << " "; }
std::cout << std::endl;
}
}