原題地址:https://oj.leetcode.com/problems/next-permutation/html
題意:算法
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).spa
The replacement must be in-place, do not allocate extra memory.code
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
htm
解題思路:blog
輸出字典序中的下一個排列。好比123生成的全排列是:123,132,213,231,312,321。那麼321的next permutation是123。下面這種算法聽說是STL中的經典算法。在當前序列中,從尾端往前尋找兩個相鄰升序元素,升序元素對中的前一個標記爲partition。而後再從尾端尋找另外一個大於partition的元素,並與partition指向的元素交換,而後將partition後的元素(不包括partition指向的元素)逆序排列。好比14532,那麼升序對爲45,partition指向4,因爲partition以後除了5沒有比4大的數,因此45交換爲54,即15432,而後將partition以後的元素逆序排列,即432排列爲234,則最後輸出的next permutation爲15234。確實很巧妙。leetcode
代碼:it
class Solution: # @param num, a list of integer # @return a list of integer def nextPermutation(self, num): if len(num) < 2: return num partition = -1 for i in range(len(num) - 2, -1, -1): if num[i] < num[i + 1]: partition = i break if partition == -1: return num[::-1] for i in range(len(num) - 1, partition, -1): if num[i] > num[partition]: num[i], num[partition] = num[partition], num[i] break num[partition + 1:] = num[partition + 1:][::-1] return num
參考致謝:io
上述代碼基於[1]進行優化
[1] http://www.cnblogs.com/zuoyuan/p/3780167.html