LeetCode 31. Next Permutation(下一组排列)
題目描述:
????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.
?????3,2,1?→?1,2,3
?????1,1,5?→?1,5,1
分析:
????題意:給定一個整型數組,根據字典序,返回它的下一個排列(如果當前給出的是最后一個排列,返回第一個排列)。
????思路:這是一道經典的排列組合題,已經存在固定的算法去解決這個問題(Next lexicographical permutation algorithm)。
????假設數組為array,長度為n,步驟如下:
????① 首先找到最大的坐標i,使得array[i - 1] < array[i]。
????② 然后找到最大的坐標j,滿足j大于等于i,且array[j] > array[i - 1]。
????③ 交換array[j]和array[i - 1]的元素。
????④?將array[i]和array[n - 1]之間的元素反轉。
????時間復雜度為O(n)。
????如果有人直接調用C++庫函數next_permutation,我竟無言以懟。
代碼:
總結
以上是生活随笔為你收集整理的LeetCode 31. Next Permutation(下一组排列)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JS替换字符串,例:加号替换成‘%2B‘
- 下一篇: 7. 嵌入式与单片机