您的位置:首页 > 其它

31. Next Permutation

2017-08-22 09:51 183 查看

 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

解读题意:题目在说啥?下一个排序的意思其实就是,给你一些数字的排列,输入某个排序A,从这些数字组成的全排列中,选出排在A后一位的排序B。例如1,2,3的全排列如下,A= 2 1 3,它的下一个排序就是B =  2 3 1

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

解题思路:直接贴张外文文献的解题方法图

1.从右向左找严格升序,找到第一个打破升序(等于也是打破的一种情况)的数字
A,下标为 index ,如图 数字 6一样

2.从右向左找第一个大于等于第一步中的数字A的数
B ,例如图中数字 7

3. 交换 A B的值

4. 逆序 index 下标之后的所有数



下面给出Python代码

class Solution(object):

def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
start = 0
end = len(nums) - 1
while end > start and nums[end] <= nums[end - 1]:
end -= 1
if end == start:  # 原序是个升序列, 直接逆序操作
nums.reverse()
return
partion = end - 1
end = len(nums) - 1
while end > partion and nums[partion] >= nums[end]:
end -= 1
change = end
nums[partion], nums[change] = nums[change], nums[partion]  #  交换两个数
nums[partion + 1:] = nums[partion + 1:][::-1]  #  逆序partion后的所有数字


欢迎点赞,留言交流
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息