LeetCode 31: Next Permutation
2015-03-24 23:17
295 查看
题目描述:
mplement 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,4,5},一共5个数字,排列的依次顺序为(如下)
{1,2,3,4,5}
{1,2,3,5,4}
{1,2,4,3,5}
{1,2,4,5,3}
{1,2,5,3,4}
{1,2,5,4,3}
……
{5,4,3,2,1}
从上面的排列可以总结出两个排列变化的规律如下:
1.从右向左找到第一个小于它右边数字的数字a
2.从a的右边找到比a大的那个数字b
3.交换a和b,那么b就在a的左边了
4.将b右边的第一个数字和最后一个数字中间的数字进行翻转
5.需要注意特殊情况,最后一个排列,直接对整个数组翻转即可。
代码:
mplement 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,4,5},一共5个数字,排列的依次顺序为(如下)
{1,2,3,4,5}
{1,2,3,5,4}
{1,2,4,3,5}
{1,2,4,5,3}
{1,2,5,3,4}
{1,2,5,4,3}
……
{5,4,3,2,1}
从上面的排列可以总结出两个排列变化的规律如下:
1.从右向左找到第一个小于它右边数字的数字a
2.从a的右边找到比a大的那个数字b
3.交换a和b,那么b就在a的左边了
4.将b右边的第一个数字和最后一个数字中间的数字进行翻转
5.需要注意特殊情况,最后一个排列,直接对整个数组翻转即可。
代码:
void nextPermutation(vector<int> &num) { vector<int>::iterator it; for(it=num.end()-1;it!=num.begin();it--){ if(*it>*(it-1)){ break; } } if(it==num.begin()){ reverse(num.begin(),num.end()); return; } vector<int>::iterator pivot = it-1; vector<int>::iterator it2; for(it2=num.end()-1;it2!=pivot;it2--){ if(*it2>*pivot){ break; } } swap(*pivot,*it2); reverse(it,num.end()); }
相关文章推荐
- leetcode 题解代码整理 31-35题
- leetcode 31. Next Permutation
- LeetCode 31~32
- Leetcode-31. Next Permutation
- LeetCode 31 Longest Valid Parentheses
- Leetcode 31. Next Permutation
- LeetCode 31
- LeetCode --- 31. Next Permutation
- LeetCode 31 Next Permutation (下一排列)
- [leetcode] 31.Next Permutation
- LeetCode 31 Next Permutation 寻找一个数字序列的比他大的最小序列
- leetcode 31. Next Permutation
- LeetCode31. Next Permutation最清晰的解法
- Leetcode题解(31)
- [leetcode] 31. Next Permutation
- Leetcode 31. Next Permutation (Medium) (cpp)
- LeetCode 31.Next Permutation
- [LeetCode] Subsets [31]
- leetcode(31) - Next Permutation
- LeetCode (31) Divide two integers (不使用 *, /, mod 求两个数相除结果)