全排列

例:对{1,2,3,4}的全排列输出。

笔试中遇到了,之前在STL中见过现成的函数,也有实现方法,但是笔试时想不起来了,只好写了个递归的。递归就是记录前序序列和剩余数字集体,依次将剩余数字集中的数字添加到前序序列中,当剩余数字集体为空时输入前序序列即可。

下面是STL库函数中的非递归实现方法:
std::next_permutation

template
bool next_permutation(BidirIt first, BidirIt last)
{
    if (first == last) return false;
    BidirIt i = last;
    if (first == --i) return false;
 
    while (true) {
        BidirIt i1, i2;
 
        i1 = i;
        if (*--i < *i1) {
            i2 = last;
            while (!(*i < *--i2))
                ;
            std::iter_swap(i, i2);
            std::reverse(i1, last);
            return true;
        }
        if (i == first) {
            std::reverse(first, last);
            return false;
        }
    }
}

你可能感兴趣的:(全排列)