Next Permutation

来源:互联网 发布:java quartz 定时服务 编辑:程序博客网 时间:2024/05/21 10:46

思路:1)算法中心思想是要找到一位,让这一位有所增加,因为右边的位数量级小,所以这一位要尽量靠右。同时,让这一位有所增加需要的那个被swap 的数肯定来自右边,因为如果来自左边,会使左边的部分减小,不符合next permutation的定义。这个swap number一定是右边的最小的那个数,最后要让右边的部分字典序最小。

算法概念:

partition number:从右往左,第一个比相邻的右边的数小的数(第一个可以从右边找到更大数字的位置,partition number右边是个递减序列)

swap number:从右往左,第一个比partition number大的数

算法框架:

1)找到partition number,说没找到说明已是最大,reverse整个数组回到最小,返回。

2)找到swap number

3) 交换 partition number 和 swap number

4) partition number后面的部分reverse

void nextPermutation(vector<int> &nums) {if (nums.size() <= 1) return;//find the  position closest to the right end, where we could find a bigger number to the rightint i = nums.size() - 2;for (; i >= 0 && nums[i] >= nums[i + 1]; --i) ;if (i < 0) reverse(nums.begin(),nums.end()); //alreay the biggest, resetelse {int j = nums.size() - 1;for (; j > i && nums[j] <= nums[i]; --j);swap(nums[i], nums[j]);reverse(begin(nums) + i + 1, end(nums));}}




0 0
原创粉丝点击