开发者

permutation computing in c++

I want to write 开发者_运维知识库a program that gets an integer n and prints all the permutations of 1,2,...,n. I know there is a recursive way to do this and I know the overhead of function calls. Is there any way to do this without recursion??


Yes, you can do it iteratively with std::next_permutation from <algorithm> as a while condition, or depending on how you set up the loop this may be one of the occasions where do...while is more appropriate.


#include <vector>
#include <algorithm>

std::vector<int> v = { 1,2,3,4,5,6,7,8,9,10 }; // see std::iota also


// important: sort v if not sorted
std::sort(v.begin(), v.end());

while (std::next_permutation(v.begin(), v.end()))
{
      // use v (unique permutation)
}
// use v: first sorted position
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜