31-NextPermutation
来源:互联网 发布:mysql front 编辑:程序博客网 时间:2024/06/05 03:22
题目:
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
分析:
这个题目是一组数字进行全排列,然后找到其中一个序列的下一个序列
NextPermutation 序列所组成的数字比上一个大,一个逆序排列的数组没有下一个排列。
主要是两个Flag
- step 1. 从右向左找到第一个比i+1 位置的数字小的i
- step 2. 从右向左找到第一个比nums[i] 大的数字nums[j](这里我采用的是从左向右)
- step 3. swap(nums,i,j)
- step 4. 将i+1 ~end 的数字进行逆序
代码:
class Solution {public: void nextPermutation(vector<int>& nums) { int len = nums.size(); int i = len - 2; while ((i >= 0) && (nums[i] >= nums[i + 1])) { i--; } int j = i+1; if (i >= 0) { while (j < len&&nums[j]>nums[i]) { j++; } swap(nums, i, j-1); } reverse(nums, i + 1); } void reverse(vector<int>& nums, int start) { int end = nums.size()-1; while (start < end) { swap(nums, start, end); start++; end--; } } void swap(vector<int>& nums, int i, int j) { int tmp = 0; tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; }};
阅读全文
0 0
- 31NextPermutation
- 31-NextPermutation
- 31-NextPermutation
- leetcode-31-NextPermutation
- Leetcode之nextPermutation
- [LeetCode]31.nextPermutation
- 常见算法问题之NextPermutation
- 31
- 31
- 31
- 31
- 31
- 31
- 31
- 31
- 31
- 2005.08.31
- -->2005.12.31
- HDU --- 4549 M斐波那契数列 【费马小定理+矩阵快速幂】
- 使用 libev 构建 TCP 响应服务器(echo server)的简单流程
- CodeForces
- c++2017-6-22语句
- java main方法参数传递
- 31-NextPermutation
- Java集合类详解
- spring cloud微服务框架 第一天
- Android数据库简单操作例子
- js获取触发事件的元素
- Drawable学习之----LevelListDrawable
- 32-Longest Valid Parentheses
- c++2017-6-22结构、联合与枚举
- 判断当前Android版本是否大于某版本