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.
1,2,3
→1,3,2
3,2,1
→1,2,3
1,1,5
→1,5,1
下一个排列问题,依稀记得STL中有一个next_permutation()算法,可以实现本功能。当然,本题要求读者手动实现,其实难度不小,但是如果想通了就很简单。
首排列是彻底的顺序,尾排列是彻底的逆序。假设前一个排列是P,后一个排列是Q。那么会有P和Q的相同前缀的长度尽可能的长。
对于一个数组1,2,5,4,3,1,它的下一个排列是1,3,1,2,4,5
因此,我们可以总结出如下规律:
从后往前看,数字应当是逐渐增大的,如上例中,增大的趋势直到2才停止,这时应当从后往前寻找第一个比2大的数也就是3。交换2和3以后,显然,该位置以后的数是逆序排序,为了使这部分的数尽可能的小,因此要逆转这部分数组。
lass Solution { public: void nextPermutation(vector<int>& nums) { int n = nums.size(); if (n <= 1) return; int i = n - 1; while (i != 0 && nums[i] <= nums[i - 1]) --i; if (i == 0) { std::reverse(nums.begin(), nums.end()); return; } --i; int j = n - 1; for (; nums[j] <= nums[i]; --j) {} std::swap(nums[i], nums[j]); std::reverse(nums.begin() + i + 1, nums.end()); return; } };
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合终身会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步