[LeetCode]Next Permutation
2015-10-04 20:14
190 查看
题目描述:(链接)
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.
解题思路:
转载链接:http://www.cnblogs.com/easonliu/p/3632442.html
把升序的排列(当然,也可以实现为降序)作为当前排列开始,然后依次计算当前排列的下一个字典序排列。
对当前排列从后向前扫描,找到一对为升序的相邻元素,记为i和j(i < j)。如果不存在这样一对为升序的相邻元素,则所有排列均已找到,算法结束;否则,重新对当前排列从后向前扫描,找到第一个大于i的元素k,交换i和k,然后对从j开始到结束的子序列反转,则此时得到的新排列就为下一个字典序排列。这种方式实现得到的所有排列是按字典序有序的,这也是C++ STL算法next_permutation的思想。
链接:http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html,具体过程见注释
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
解题思路:
转载链接:http://www.cnblogs.com/easonliu/p/3632442.html
把升序的排列(当然,也可以实现为降序)作为当前排列开始,然后依次计算当前排列的下一个字典序排列。
对当前排列从后向前扫描,找到一对为升序的相邻元素,记为i和j(i < j)。如果不存在这样一对为升序的相邻元素,则所有排列均已找到,算法结束;否则,重新对当前排列从后向前扫描,找到第一个大于i的元素k,交换i和k,然后对从j开始到结束的子序列反转,则此时得到的新排列就为下一个字典序排列。这种方式实现得到的所有排列是按字典序有序的,这也是C++ STL算法next_permutation的思想。
链接:http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html,具体过程见注释
class Solution { public: void nextPermutation(vector<int>& nums) { int i; int j; // From right to left, find the first item(PartitionNumber) which violate the increase trend for (i = nums.size() - 2; i >= 0; --i) { if (nums[i] < nums[i + 1]) { break; } } // From right to left, find the first item(ChangeNumber) which is larger than PartitionNumber for (j = nums.size() - 1; j >= i ; --j) { if (nums[j] > nums[i]) { break; } } // swap PartitionNumber and ChangeNumber if (i >= 0) { swap(nums[i], nums[j]); } // reverse all after PartitionNumber index reverse(nums.begin() + i + 1, nums.end()); } };
相关文章推荐
- 条款5.了解c++默默编写并且调用了哪些函数。
- python有些错误换行问题解决
- 条款4:确保对象在使用之前就已经被初始化了
- UVALive 6508 Permutation Graphs
- 网络故障之DHCP广播风暴------运维上看交换机的CPU占用率100%
- 左右JAVA示例代码事件分发和监督机制来实现-绝对原创有用
- 核心技术篇:6.android网络编程之json解析
- 机器学习笔记 线性判别分析(中)
- STC12C4052AD,4位数据总线驱动1602 LCD液晶屏,8位ADC功能,0--255级别
- 动态变量和静态变量的区别
- 动态规划(算法分析与设计)
- 自己的练习四之对象与数组的组合
- iOS 转场动画等
- 信息安全系统设计基础第三周学习总结
- UVALive 4853 Emoogle Balance
- ASP.NET MVC + Bootstrap + XML + WCF 封装短信验证服务(一)
- AOP运行过程解析
- 第二次作业利用java语言编写计算器进行四则运算
- 自己的练习三之复制构造函数
- MFC Radio Button 和 Combox Button的简单操作