【題目描述】
Given a list of integers, which denote a permutation.Find the next permutation in ascending order.
Notice:The list may contains duplicate integers.
給定一個整數(shù)數(shù)組來表示排列正什,找出其之后的一個排列移宅。
注意:排列中可能包含重復(fù)的整數(shù)
【題目鏈接】
www.lintcode.com/en/problem/next-permutation/
【題目解析】
找下一個升序排列摔刁,C++ STL 源碼剖析一書中有提及掠河,Permutations 一小節(jié)中也有詳細(xì)介紹扣甲,下面簡要介紹一下字典序算法:
從后往前尋找索引滿足 a[k] < a[k + 1], 如果此條件不滿足担平,則說明已遍歷到最后一個却特。
從后往前遍歷救崔,找到第一個比a[k]大的數(shù)a[l], 即a[k] < a[l].
交換a[k]與a[l].
反轉(zhuǎn)k + 1 ~ n之間的元素惶看。
由于這道題中規(guī)定對于[4,3,2,1], 輸出為[1,2,3,4], 故在第一步稍加處理即可。
【參考答案】