LeetCode算法题目:Next Permutation
来源:互联网 发布:多益网络校招登录 编辑:程序博客网 时间:2024/05/22 01:30
题目:
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
分析:
字典序法就是按照字典排序的思想逐一产生所有排列。
例如,由1,2,3,4组成的所有排列,从小到大的依次为:1234, 1243, 1324, 1342, 1423, 1432,
2134, 2143, 2314, 2341, 2413, 2431,
3124, 3142, 3214, 3241, 3412, 3421,
4123, 4132, 4213, 4231, 4312, 4321.分析这种过程,看后一个排列与前一个排列之间有什么关系?
再如,设有排列(p)=2763541,按照字典式排序,它的下一个排列是什么?
276 35 41 (找最后一个正序35)
27635 4 1 (找3后面比3大的最后一个数4)
276 4 5 3 1 (交换3,4的位置)
2764 135 (把4后面的5,3,1反转)
下面给出求 p[1…n] 的下一个排列的描述:
- 求 i = max{j | p[j – 1] < p[j]} (找最后一个正序)
- 求 j = max{k| p[i – 1] < p[k]} (找最后大于 p[i – 1] 的)
- 交换 p[i – 1] 与 p[j]得到 p[1] … p[i-2] p[j] p[i] p[i+1] … p[j-1] p[i-1] p[j+1] … p[n]
- 反转 p[j] 后面的数得到 p[1] … p[i-2] p[j] p[n] … p[j+1] p[i-1] p[j-1] … p[i]
代码:
class Solution {public: void nextPermutation(vector<int>& nums) { int i,j; int length= nums.size(); for (i=length-2;i>=0;i--) { if(nums[i+1]>nums[i]) { for(j=length-1;j>=0;j--) { if(nums[j]>nums[i]) break; } swap(nums[i],nums[j]); reverse(nums.begin()+i+1,nums.end()); return; } } reverse(nums.begin(),nums.end()); return; }};
- LeetCode算法题目:Next Permutation
- LeetCode算法题之Next Permutation
- 算法作业HW23:LeetCode 31 Next Permutation
- LeetCode算法题——Next Permutation
- 【LeetCode算法练习(C++)】Next Permutation
- leetcode做题总结,题目Next Permutation 31
- LeetCode: Next Permutation
- LeetCode Next Permutation
- LeetCode : Next Permutation
- [Leetcode] Next Permutation
- [LeetCode] Next Permutation
- [Leetcode] Next Permutation
- leetcode 88: Next Permutation
- [LeetCode]Next Permutation
- LeetCode-Next Permutation
- [leetcode]Next Permutation
- LeetCode - Next Permutation
- LeetCode 31: Next Permutation
- 存储过程实现开窗函数功能
- Quartz说明及使用
- keil编译出错关于__use_no_semihosting_swi的使用
- JS学习之路(二)---函数
- 常见机器学习算法
- LeetCode算法题目:Next Permutation
- Sphinx匹配模式详解
- JavaScript中return的用法详解
- ubuntu格式化优盘为fat32
- 常用shell (一)
- Android中Canvas绘图基础详解
- spring jpa CrudRepository save 新建数据没有返回id
- Unity游戏内下载APK并安装遇到JNI ERROR (app bug): accessed stale local reference 0x1d200001 (index 0 in a table
- 细粒度图像识别算法Mask-CNN 论文笔记