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

又一道permutation的题目,题目要求inplace,所以很明显,类似于permutation那种全部求出结果再查找的方法肯定不行,只有真正找到词典序的规律。记得之前组合数学课上曾经学过这种,当时怎么都没想明白书中给的方法,没想到这题结合举例分析,竟然想出了和i书中方法完全一样的解法,甚为开心呐~

总体思路如下:

1.从前向后找一个严格递增的子序列,将递增子序列的最后一个i记为up。

2.因为up及之后的数字组成了一个非递增序列,所以改变后面的数字排序不能得到下一个更大的数字。所以需要修改的是up-1这个位上的数,即nums[up:]中比nums[up-1]大的最小值,也即将其修改为nums[up:]中最后一个比其大的数字,(因为是非递增序列)。找到这个index,交换nums[index],nums[up-1]

3.将nums[up:]逆序,其实是做一次升序排序,但是考虑交换nums[index],nums[up-1]后,nums[up:]依然为非递增序列,所以只要reverse就可以。

举个例子,7 2 5 3 3 1。先找到 up为2,则nums[up-1]为2,nums[up:] 中比2大的最小值为3,注意是取最后一个3,方便第3步直接reverse,获得增序排序。

交换数字之后成为 7 3 5 3 2 1,然后对5321做一个逆序,获得最终的排序为7 3 1 2 3 5。

可以看到最多扫描三次, up 为0时,直接reverse,扫描两次。空间复杂度为O(1),代码如下:

class Solution(object):
    def nextPermutation(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        up = 0
        for i in xrange(1,len(nums)):
            if nums[i] > nums[i-1]:
                up = i
        if up == 0:
            nums.reverse()
        else:
            index = up
            for i in xrange(up,len(nums)):
               if nums[i] >  nums[up-1]:
                   index = i
            nums[up-1], nums[index] = nums[index], nums[up-1]
            for i in xrange((len(nums) - up)/2):
                nums[up + i], nums[len(nums)-1-i] = nums[len(nums)-1-i], nums[up+i]
时间: 2024-10-14 05:11:18

Next Permutation的相关文章

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 replaceme

Permutation Sequence

The set [1,2,3,-,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order,We get the following sequence (ie, for n = 3): "123" "132" "213" "231" "312" "3

LeetCode 31. Next Permutation

Problem: https://leetcode.com/problems/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 poss

60. Permutation Sequence

The set [1,2,3,…,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order,We get the following sequence (ie, for n = 3): "123" "132" "213" "231" "312" "3

【数组】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 repla

[LeetCode]题解(python):031-Next Permutation

题目来源 https://leetcode.com/problems/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

HDU3664 Permutation Counting

Permutation Counting Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1487    Accepted Submission(s): 754 Problem Description Given a permutation a1, a2, … aN of {1, 2, …, N}, we define its E-val

UVALive 6508 Permutation Graphs

Permutation Graphs Time Limit: 3000ms Memory Limit: 131072KB This problem will be judged on UVALive. Original ID: 650864-bit integer IO format: %lld      Java class name: Main 解题:逆序数 1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long l

CF 500 B. New Year Permutation 并查集

User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible. Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≤ k