看侯捷的STL源码剖析,讲述了一个next_permutation的算法,用于计算排列组合。
template<class BidirectionalIterator>
bool next_permutation(BidirectionalIterator first,BidirectionalIterator last)
{
if(first==last) return false;
BidirectionalIterator i;
i=last;
if(--i==first) return false;
i=last;
--i;
for(;;)
{
BidirectionalIterator ii=i;
--i;
if(*i<*ii)
{
BidirectionalIterator j=last;
while(!(*i<*--j));
iter_swap(i,j);
reverse(ii,last);
return true;
}
if(i==first)
{
reverse(first,last);
return false;
}
}
}