[leetcode]排列类问题
来源:互联网 发布:知乎和百度关系 编辑:程序博客网 时间:2024/06/06 06:52
31. 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,2,3 → 1,3,23,2,1 → 1,2,31,1,5 → 1,5,1
Algorithm from wikipedia:
Find the largest index k
such that a[k] < a[k + 1]
. If no such index exists, the permutation is the last permutation.
Find the largest index l
greater than k
such that a[k] < a[l]
.
Swap the value of a[k]
with that of a[l]
.
Reverse the sequence from a[k + 1]
up to and including the final element a[n]
.
void nextPermutation(vector<int>& nums){ int n = nums.size(); if (n <= 1) return; int i; // get the rightmost that nums[i] < nums[i + 1] for (i = nums.size() - 2; i >= 0 && nums[i] >= nums[i + 1]; --i); if (i == -1) { reverse(nums.begin(), nums.end()); return; } int j; // get the rightmost nums[j] that nums[j] > nums[i] for (j = i + 1; j < nums.size() && nums[i] < nums[j]; ++j); swap(nums[i], nums[--j]); // reverse from i + 1 to the end reverse(nums.begin() + i + 1, nums.end());}
阅读全文
0 0
- [leetcode]排列类问题
- Leetcode全排列问题
- LeetCode 46 47....排列问题
- Leetcode全排列问题Java版
- [LeetCode]Next Permutation下一个排列问题
- leetcode之全排列问题(Permutations)
- LeetCode OJ-46.Permutations(全排列问题)
- LeetCode 数字排列问题 46 Permutations
- leetcode 46. Permutations 全排列问题+递归
- LeetCode—**字符串中数字的全排列问题Permutations
- 【LeetCode】6.ZigZag Conversion N型排列问题
- leetcode 46,47. Permutations I/II 全排列问题 java
- 全排列,字典顺序问题 ( permutations/leetcode)
- 排列问题
- 排列问题
- 排列问题
- 排列问题
- 排列问题
- 《Android群英传》笔记7——事件拦截机制分析
- JDBC常见错误
- 2017年上海金马五校程序设计竞赛(网上资格赛) Problem J : Raising Bacteria
- springMVC-笔记009-编码过滤器
- 基于bfs搜索算法的迷宫最短路径游戏
- [leetcode]排列类问题
- sql server 删除带默认值的字段
- Java 变相实现 goto
- 学习淘淘商城第七十七课(LVS+Nginx负载均衡---上篇)
- 1193: 谁拿了最多奖学金?
- python继承
- 数据库视图的理解和使用
- Python基础学习(7)
- python密码学编程(一)