【leetcode刷题笔记】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 1,2,31,3,2
2 3,2,11,2,3
3 1,1,51,5,1

题解:字典序法

步骤:

1.从右向左找出第一个比它右边数字小的数,记为a;

2.找出a右边比它大的最小的数,记为b;

3.交换a和b;

4.reverse原来a所在位置后面所有的元素。

代码:

复制代码
 1 class Solution {
 2 public:
 3     void nextPermutation(vector<int> &num) {
 4         int n = num.size();
 5         int j;
 6         for(j = n-2;j >= 0;j --){
 7             if(num[j] < num[j+1])
 8             {
 9                 //与右边比它大的最小的数互相换位
10                 int min_index = n-1;
11                 int minmum = 32767;
12                 for(int u = n-1;u > j;u --)
13                     if(num[u] > num[j]){
14                         if(num[u] < minmum){
15                             min_index = u;
16                             minmum = num[u];
17                         }
18                         break;
19                     }
20 
21                 char temp = num[min_index];
22                 num[min_index] = num[j];
23                 num[j] = temp;
24                 reverse(num.begin()+j+1,num.end());
25                 break;
26 
27             }
28         }
29         if(j < 0)
30             reverse(num.begin(),num.end());
31     }
32 };
复制代码

有一种类似321这种序列的情况,它的下一个排列是123,字典序法是找不出来的,所以在代码29行单独加了一个判断,如果遇到这样的序列,直接倒置返回就可以了。

posted @   SunshineAtNoon  阅读(150)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示