[Leetcode] Next Permutation

題目鏈接:https://oj.leetcode.com/problems/next-permutation/

Description

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

乍看,題目描述不是很明白,大概的意思是,把有序的排列作為已有序列(左列),然后依次計算當前排列的下一個字典序排列。

算法思想

對當前排列從后向前掃描,找到一對為升序的相鄰元素,記為i和j(i < j)。如果不存在這樣一對為升序的相鄰元素,則所有排列均已找到,算法結束;否則,重新對當前排列從后向前掃描,找到第一個大于i的元素k,交換i和k,然后對從j開始到結束的子序列反轉,則此時得到的新排列就為下一個字典序排列。這種方式實現(xiàn)得到的所有排列是按字典序有序的,這也是C++ STL算法next_permutation的思想。

AC代碼

https://oj.leetcode.com/submissions/detail/8683079/

相關知識:permutation,?lexicographical

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容