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