leetcode 题解 || Next Permutation 问题

来源:互联网 发布:港融大数据平台不好使 编辑:程序博客网 时间:2024/04/29 21:37

problem:

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

Hide Tags
 Array


题意:

给一个序列,找出下一个紧挨着的序列。比如 1 ,2, 3 的下一个序列是  1, 3 ,2  ;

注意: 3 ,2 ,1 的下一个序列 是它的反转: 1 ,2 ,3



thinking:

(1)这是排列组合算法的一种实现方法,难点在于找到紧挨着该序列的 下一个序列

(2)这里采用了 STL :

【STL】next_permutation的原理和使用

精华在于,从序列的后端逆序比较,比如 1 ,2, 3 的下一个序列是  1, 3 ,2  ,这样只需交换 2,3即可。
对于序列1, 2, 5, 4, 3:逆序寻找到2 , 5,发现这两个元素是顺序的,则从尾部逆序寻找一个比2 大的数,这里是3,和2 交换位置,变成1 ,3 ,5 ,4 ,2 
最后再,反转5, 4, 2 即可得到下一个序列: 1 ,3 ,2, 4, 5 

code:

class Solution {public:    void nextPermutation(vector<int> &num) {        vector<int>::iterator first = num.begin();        vector<int>::iterator last = num.end();        vector<int>::iterator tmp = first;        if(++tmp == last)            return;        vector<int>::iterator i  = last;        i--;        for(;;) {            vector<int>::iterator ii = i;            --i;            /*            *从尾部逆序比较两个相邻的元素,如果尾部m个元素一直是逆序的,说明尾部已经足够大            *这时需要不断往头部移动,直到找到一对顺序的相邻元素i、ii,再从尾部找一个比i还小的元素j            *先交换i 和  j元素,再将ii~last之间的元素反转            */            if(*i < *ii) {                vector<int>::iterator j = last;                while(!(*i < *--j));                iter_swap(i, j);//与swap()稍有不同,iter_swap()的参数是对迭代器的引用                reverse(ii, last);                return;            }            if(i == first) {                reverse(first, last);  //全逆向,即为最小字典序列,如cba变为abc                return;            }        }//for    }};


0 0