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
题意:
给一个序列,找出下一个紧挨着的序列。比如 1 ,2, 3 的下一个序列是 1, 3 ,2 ;
注意: 3 ,2 ,1 的下一个序列 是它的反转: 1 ,2 ,3
thinking:
(1)这是排列组合算法的一种实现方法,难点在于找到紧挨着该序列的 下一个序列
(2)这里采用了 STL :
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 } };
leetcode 题解 || Next Permutation 问题
原文:http://blog.csdn.net/hustyangju/article/details/44591937