題目鏈接: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開始到結束的子序列反轉(zhuǎn)衷敌,則此時得到的新排列就為下一個字典序排列勿侯。這種方式實現(xiàn)得到的所有排列是按字典序有序的,這也是C++ STL算法next_permutation的思想缴罗。
AC代碼
https://oj.leetcode.com/submissions/detail/8683079/
相關知識:permutation,?lexicographical