31. Next Permutation
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
题意:
实现给定数组序列的下一个排列,重新排列的数字序列比以前数字的字典序列更大。
如果这种字典序增大序列不存在,即现在给定的数组序列是最大的字典序序列,则直接按升序排序,即字典序排列最小。
思路:
方法一:
利用C++STL库中的next_permutation()函数,函数详情next_permutation()。
1 | class Solution { |
方法二:
1 | 1 2 3 4 |
根据上面的1 2 3 4的字母逻辑递增顺序可以得到以下规律:从后往前查找(正常顺序递增),第一个变小的位置i后的元素进行反转,然后再在反转后的元素中找到第一个比i元素大的元素进行互换,就可以得到比此排列大的一个排列。
1 | class Solution { |
Java Code:
1 | class Solution { |
1 | class Solution { |