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
题意:
给一个序列,找出下一个紧挨着的序列。比如 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
- leetcode 题解 || Next Permutation 问题
- LeetCode题解:Next Permutation
- LeetCode题解:Next Permutation
- leetcode题解-31. Next Permutation
- leetcode题解-31. Next Permutation
- Leetcode题解-31. Next Permutation
- LeetCode 题解(4):Next Permutation
- Leetcode之Next Permutation 问题
- [LeetCode]Next Permutation下一个排列问题
- 【leetcode 排列组合问题】Next Permutation | Permutations | Permutations II | Permutation Sequence
- LeetCode: Next Permutation
- LeetCode Next Permutation
- LeetCode : Next Permutation
- [Leetcode] Next Permutation
- [LeetCode] Next Permutation
- [Leetcode] Next Permutation
- leetcode 88: Next Permutation
- [LeetCode]Next Permutation
- 关于JAVA string.split()方法。
- Jquery dataTable 向服务器传额外参数
- warning C4552: '>>' : operator has no effect; expected operator with side-effect
- msyql 分组前几名sql
- UVa 10047 The monocycle (BFS)
- leetcode 题解 || Next Permutation 问题
- java object类
- C#自动生成word报告
- 黑马程序员——OC基础语法—@property和@synthesize使用
- wait()方法和 sleep()方法的区别是什么?
- linux c下使用正则表达式
- iOS 定位没有弹出请求提示框和调用代理方法
- Android系统中标准Intent的使用√
- Windows环境下Android Studio v1.0安装教程