<LeetCode OJ> 31. Next Permutation
2017-06-28 10:39
225 查看
31. Next Permutation
Total Accepted: 54346 TotalSubmissions: 212155 Difficulty: Medium
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
STL来做,秒杀
class Solution { public: void nextPermutation(vector<int>& nums) { next_permutation(nums.begin(), nums.end()); } };
此题感觉没多大意思。不好高速想出规律:
可是比較明显的规律是:
1。升序为最小组合,降序为最大组合
2,某一个数的下一个数,就是比他大的最小组合数。比方123,下一个比他大的最小组合就是132,必须从低位处理
3,stl的处理就是从低位(数组末尾)開始找起,
a)找到首个相邻的升序序列。将前一个数据与比其首次大的数交换(然后逆置后面的数)比方:123543为124533(首个升序3,5。可是4是首次比3大,则交换),此处的操作意义就是使数通过首个升序变大。
b)显然此数不是大于原数的最小数,而且后面的数逆置后才是最小的,即124533为124335。so,done!
。
//思路首先(不调用库函数): //举例:abc,acb,bac,bca,cab,cba class Solution { public: void nextPermutation(vector<int>& nums) { if(nums.empty() || nums.size()==1) return; vector<int>::iterator ite1=nums.end(); ite1--; while(true) { vector<int>::iterator ite2=ite1; ite1--;//ite1始终在ite2前面一个位置(左边算作最前面) if(*ite1 < *ite2)//升序已经出现。接着又一次从后面找首个升序位置 { vector<int>::iterator itej=nums.end(); while(!(*ite1 < *--itej)); iter_swap(ite1,itej);//找到首个升序序列将其交换 reverse(ite2,nums.end()); return; } if(ite1==nums.begin()) { reverse(nums.begin(),nums.end()); return; } } } };
注:本博文为EbowTang原创,兴许可能继续更新本文。假设转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50450861
原作者博客:http://blog.csdn.net/ebowtang
參考资源
【1】侯捷。《STL源代码剥析》
相关文章推荐
- <LeetCode OJ> 28. Implement strStr()
- <LeetCode OJ>Rotate Array【189】
- <LeetCode OJ> Find Minimum in Rotated Sorted Array【153】
- <LeetCode OJ>Implement Stack using Queues【225】
- <LeetCode OJ> 62. Unique Paths
- <LeetCode OJ>Implement Queue using Stacks【232】
- <LeetCode OJ> Nim Game【292】
- <LeetCode OJ> Min Stack【155】
- <LeetCode OJ> Longest Increasing Subsequence【300】
- <LeetCode OJ> Maximum Subarray【53】
- <LeetCode OJ> 326. Power of Three
- <LeetCode OJ> Happy Number【202】
- <LeetCode OJ> Move Zeroes【283】
- <LeetCode OJ>Valid Parentheses【20】
- <LeetCode OJ> 55. Jump Game
- <LeetCode OJ> 168. Excel Sheet Column Title
- <LeetCode OJ>Remove Element【27】
- <LeetCode OJ>Single Number( I / II / III )【136 / 137 / 260】
- <LeetCode OJ>Factorial Trailing Zeroes【172】
- <LeetCode OJ>Delete Node in a Linked List【237】