dfs 之 下一个排列

52. 下一个排列

中文English

给定一个整数数组来表示排列,找出其之后的一个排列。

Example

例1:

输入:[1]
输出:[1]

例2:

输入:[1,3,2,3]
输出:[1,3,3,2]

例3:

输入:[4,3,2,1]
输出:[1,2,3,4]

Notice

排列中可能包含重复的整数

遇到这种题目,只能自己找找规律:

1 5 2 3 4 / /
1 5 2 4 3 (2 1) / \ / \
1 2 3 4 5 / down swap 2 only
5 4 3 2 1 \ up ==> 极端情形(独一) (1)场景
5 2 3 1 0 \ / \ up down ==> swap(min2(down), find greater than min2), then sort left (2)场景

基本上场景就是看你数据考虑是否全面。

通过观察总结起来的做法就是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution:
    """
    @param nums: A list of integers
    @return: A list of integers
    """
    def nextPermutation(self, nums):
        # write your code here
        n = len(nums)
        i = n-1
        while i > 0 and nums[i] <= nums[i-1]:
            i -= 1
         
        if i == 0:
            return nums[::-1]
         
        assert nums[i] > nums[i-1]
 
 
        greater_index = i
        for j in range(i+1, n):
            if nums[j] > nums[i-1]:
                greater_index = j
            else:
                break
         
        assert nums[greater_index] > nums[i-1]
         
        nums[greater_index], nums[i-1] = nums[i-1], nums[greater_index]
         
        return nums[0:i] + sorted(nums[i:])

  

posted @   bonelee  阅读(151)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示