您的位置:首页 > 编程语言 > Python开发

31. Next Permutation Leetcode Python

2015-01-22 06:43 351 查看
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



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python leetcode Array