31 Next Permutations【M】【19】

本文介绍了一个算法问题:如何在原地将一组数字重新排列为字典序中下一个更大的排列。如果无法形成更大的排列,则将其变为最小的排列(升序)。文章通过示例说明了该问题,并提供了一种解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


Subscribe to see which companies asked this question


算的还是挺麻烦的,用最naive的方法做的。。。理论上应该还有更棒的。。。。。。



class Solution(object):
    def nextPermutation(self, nums):

        t = 0

        a = nums[:]
        a.sort(reverse = True)
        if a[:] == nums[:]:
            nums.reverse()
            return

        l = len(nums)

        if l == 1:# or nums == nums[::-1]:
            return

        t = l - 1
        while t >= 0 and nums[t] > nums[t-1]:
            t -= 1

        if l - t > 1:
            nums[l-1],nums[l-2] = nums[l-2],nums[l-1]
            return

        if t == l - 1:
            while t > 0 and nums[t] <= nums[t-1]:
                t -= 1
            a = nums[t-1:l][::-1]
            a.sort()
            pos = a.index(nums[t-1],0,len(a)) + 1
            while a[pos] == a[pos - 1]:
                pos += 1
            nums[t-1] = a[pos]
            del a[pos]
            nums[t:l] = a[:]
            return





# T451856 排列间的距离(不能用vector ) ## 题目描述 小L最近迷上了全排列,对于一个长度为 $n$ 的排列 $s$(`string` 类型),里面包含**字典 $dic$ 中的前 $n$ 个字母**。字典 $dic$ 为:`abcefghijklnopqrstvwxyz`(即 `a` 至 `z` 中除了 `d`、`m` 和 `u` 以外的所有小写字母)。 对于长度为 $n$ 的任意一个排列 $s$,字典 $dic$ 中的前 $n$ 个字母都恰好出现一次。那么,如果将所有长度为 $n$ 的排列按字典序排好序,一定能够构成一个有序的 `string` 数组 $p[1\sim n!]$。 对于一个排列 $s$,有两种转移操作: - 转移到字典序比 $s$ 大的下一个排列。如果当前排列 $s$ 已经是最后一个排列,那么 $s$ 的下一个排列就是字典序第一的排列 - 转移到字典序比 $s$ 小的上一个排列。如果当前排列 $s$ 是第一个排列,那么 $s$ 的上一个排列就是字典序最后一个的排列 现在小L有 2 个排列 `A` 和 `B`,现在他想知道,在只有上述两种转移操作的前提下,排列 `A` 最少转移多少次能得到排列 `B`? ## 输入格式 第一行一个整数 $n$,代表排列的长度 第二行一个长度为 $n$ 的字符串,代表排列 `A` 第三行一个长度为 $n$ 的字符串,代表排列 `B` ## 输出格式 一行一个整数代表排列 `A` 转移到 `B` 的最少步数(排列 `A` 到 `B` 的距离) ## 输入输出样例 #1 ### 输入 #1 ``` 5 abcef bafec ``` ### 输出 #1 ``` 29 ``` ## 输入输出样例 #2 ### 输入 #2 ``` 5 abcef fecba ``` ### 输出 #2 ``` 1 ``` ## 说明/提示 $30\%$ 的数据,$1\le n\le 10$ $100\%$ 的数据,$1\le n\le 19$
最新发布
05-14
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值