字典顺序排列的问题也经常碰到,现在习惯直接使用next_permutation函数,你要我返回第几个我就返回第几个。

对应的,next_permutation(start,end)和prev_permutation(start,end)。这两个函数作用是一样的,区别就在于前者求的是当前排列的下一个排列,后一个求的是当前排列的上一个排列。

Leetcode60.Permutation Sequence为例:要求的是给定n长度的序列,进行全排列之后的第k个。先把我写的放出来:

//直接用STL中的next_permutation函数
//由于是返回一个Bool型的,因此放在while里,并且用数组来模拟过程
class Solution {
public:
    string getPermutation(int n, int k) {
        string res;
        vector<int> vec;
        for(int i=1;i<=n;++i)
            vec.push_back(i);
        do{
            if(--k<=0)
                break;
        }while(next_permutation(vec.begin(),vec.begin()+n));
        for(int i=0;i<vec.size();++i)
            res+=to_string(vec[i]);
        return res;
    }
};

那么几个点注意一下:

1.首先,妈耶do while循环很久没有用过了,这里为什么要先进行判断体再来while判定?因为此时如果我给定k=1,那么如果我先不判定k,而是先进行next_permutation的判断,那么其实我已经多进行了一次排列,已经过头了一个,对吧。

2.next_permutation返回的是bool型的变量,因此没有问题,放在while判断中即可

对于next_permutation函数,其函数原型为:

     #include <algorithm>

     bool next_permutation(iterator start,iterator end)

那么对于具体的实现,我觉得这篇写的还是通俗的,可以看一下:

https://blog.csdn.net/love20165104027/article/details/79809291