博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode——31. Next Permutation
阅读量:4137 次
发布时间:2019-05-25

本文共 1386 字,大约阅读时间需要 4 分钟。

题目

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

AC代码

思路很简答,就是利用下一个全排列性质,具体见上一博客。

代码解释也很清楚!

class Solution {public:    void nextPermutation(vector
& nums) { //先检查nums中是不是递减的 bool decending=true;//假设递减 for(int i=0;i
=1;i--) { if(nums[i]<=nums[i-1]) continue;//有等号是为了考虑重复元素 else { pivot=nums[i-1]; p_index=i-1;//记录pivot的下标 break; } } //然后寻找右边最大递减子序列所有比pivot大的元素中最小的那个,和pivot交换 for(int i=nums.size()-1;i>=0;i--) { if(nums[i]>pivot)//一定要找到严格大于pivot的,不能带等号,肯定会有的 { swap(nums[i],nums[p_index]); break; } } //然后调换右边最大递减子序列的顺序 for(int i=p_index+1;i<=(p_index+nums.size())/2;i++) swap(nums[i],nums[nums.size()+p_index-i]); } }};

转载地址:http://pexvi.baihongyu.com/

你可能感兴趣的文章
HDU 5461 Largest Point(2015沈阳赛区网络赛+技巧水题)
查看>>
HDU 5464 Clarke and problem(DP 01背包)
查看>>
HDU 5455 Fang Fang(2015沈阳赛区网络赛)
查看>>
HDU 2571 命运(DP)
查看>>
HDU 2955 Robberies(01背包+概率)
查看>>
HDU 1203 I NEED A OFFER!(01背包+概率)
查看>>
HDU 1238 Substrings(求公共正反向连续子串)
查看>>
HDU 2717 Catch That Cow(哎!居然没想到用bfs)
查看>>
HDU 25919 新生晚会(水题组合问题)
查看>>
HDU 2612 Find a way(两次bfs)
查看>>
HDU 2188 选拔志愿者(简单博弈+记忆化)
查看>>
HDU 5493 Queue(线段树)
查看>>
HDU 5563 Clarke and five-pointed star(暴力)
查看>>
HDU 3951 Coin Game(博弈取对称思路)
查看>>
HDU 4920 Matrix multiplication(简单矩阵相乘+技巧减少Mod次数)
查看>>
HDU 4525 威威猫系列故事——吃鸡腿(水题,合并递推公式就行)
查看>>
HDU 4561 连续最大积
查看>>
HDU 4557 非诚勿扰 (简单模拟)
查看>>
HDU 4550 卡片游戏(贪心+细心)
查看>>
蓝桥杯 算法训练 集合运算
查看>>