31. Next Permutation Leetcode Python

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

先贴一个不能过的算法,是来自前面的permutaion的解法,用一个used array去标记哪些点用过了。 因为要开辟新空间所以没有过。

用的是bfs 可以标记len(solution)=2时候返回得到的solution[-1]就是所要的permutation

class Solution:
    # @param num, a list of integer
    # @return a list of integer
    def findperm(self,num,solution,valuelist,used):
        if len(solution)==2:
            return solution
        elif len(valuelist)==len(num):
            solution.append(valuelist)
        for index in range(len(num)):
            if used[index]==False:
                valuelist=valuelist+[num[index]]
                used[index]==True
                self.findperm(num,solution,valuelist,used)
                valuelist=valuelist[:len(valuelist)-1]
                used[index]=False

    def nextPermutation(self, num):
        if len(num)<=1:
            return num
        used=[False for index in range(len(num))]
        solution=[]
        self.findperm(num,solution,[],used)
        return solution[-1]

第二个解法来自 http://blog.csdn.net/m6830098/article/details/17291259

但是python里面略有不同,我要先反序找出递增的元素 比如 1234 得到3

然后再反序 找出第一个比3大的数, 二者交换得到1243 再将 124 后面的元素排序。

<pre name="code" class="python">class Solution:
    # @param num, a list of integer
    # @return a list of integer
    def nextPermutation(self, num):
        lenth=len(num)-1
        while lenth>0:
            if num[lenth-1]<num[lenth]:
                break
            lenth-=1
        if lenth==0:
            num.reverse()
        k=len(num)-1
        while k>=lenth:
            if num[k]>num[lenth-1]:
                break
            k-=1
        num[k],num[lenth-1]=num[lenth-1],num[k]
        newnum=num[lenth:]
        newnum.sort()
        num[lenth:]=newnum
        return num


 





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值