31. Next Permutation
来源:互联网 发布:财神软件 编辑:程序博客网 时间:2024/06/06 19:14
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
这题属于找规律题,不需要运用典型算法,就是理清楚下一个permutation的出现遵循什么规律。主要是三步:
1. 从右往左找到第一个比右边小的数,即nums[i] < nums[i + 1];
2. 然后在i 的右侧找最小的比nums[i]大的数nums[j];
3. 交换i 和 j 然后对i 右侧数组重新sorting。
代码:
void nextPermutation(vector<int>& nums) { int len = nums.size(); if (len <= 1) return; int i; for (i = len - 2; i >= 0; i--) { if (nums[i] < nums[i + 1]) break; } if (i < 0) { sort(nums.begin(), nums.end()); return; } int pos = i; int next = i + 1; for (i = pos + 1; i < len; i++) { if (nums[i] < nums[next] && nums[i] > nums[pos]) next = i; } int temp = nums[pos]; nums[pos] = nums[next]; nums[next] = temp; sort(nums.begin() + pos + 1, nums.end());}
阅读全文
0 0
- [LeetCode]31.Next Permutation
- LeetCode --- 31. Next Permutation
- [Leetcode] 31. Next Permutation
- LeetCode 31.Next Permutation
- 31. Next Permutation
- [leetcode] 31.Next Permutation
- [leetcode] 31. Next Permutation
- *LeetCode 31. Next Permutation
- 31. Next Permutation
- Leetcode 31. Next Permutation
- 31. Next Permutation
- 31. Next Permutation
- 31. Next Permutation
- leetcode 31. Next Permutation
- 31. Next Permutation LeetCode
- 31. Next Permutation
- 31. Next Permutation
- 31. Next Permutation
- 约瑟夫环(Josephuse)
- Git&&GitHub【速成】-(6)-Git之发现优秀开源项目
- C和指针之数组编程练习5 (矩阵相乘)
- 76. Minimum Window Substring
- 九九乘法表
- 31. Next Permutation
- iOS GIF合成有透明通道图片重叠问题
- phpcms二次开发流程
- 阿里云海外服务器80端口无法启动
- 如何像 NASA 顶级程序员一样编程 — 10 条重要原则(转载)
- filepath = XmlUtils.class.getClassLoader().getResource("users.xml").getPath();无法处理空格( )
- LintCode167:链表求和
- [Lua]在C函数中保存状态--注册表,环境表,upvalue
- 爬虫总结