LeetCode 31. Next Permutation
来源:互联网 发布:玻璃雕花机编程 编辑:程序博客网 时间:2024/06/06 01:36
问题
https://leetcode.com/problems/next-permutation/
方法
原文:http://blog.csdn.net/cpfeed/article/details/7376132
1, 使用STL 中的next_permutation函数。
2, 自己实现next_permutation;
分为四个步骤:
a, 从后往前找到第一个非递增的元素A[i]; 即 i = max{i| A[i] < A[i+1]}
b, 在i往后的元素中找到比元素i大的最小元素A[k]; (由于从i+1 的数是递增的因此只要找到最后一个大于A[i] 的元素就是A[k]);
c, 交换A[i] A[k];
d, 将i之后所有元素逆序。
class Solution {public: void reverse(vector<int>& nums, int i) { int L = i; int R= nums.size()-1; while(L< R){ swap(nums[L++], nums[R--]); } } void nextPermutation(vector<int>& nums) { if (nums.size() < 2) return ; int i; for(i=nums.size()-2; i>=0; --i){ // first < if (nums[i] < nums[i+1]) break; } if (i>=0) { int k; for(int j=i+1; j <nums.size(); ++j) // last > A[i] if (nums[j] > nums[i]) k = j; else break; swap(nums[i], nums[k]); reverse(nums, i+1); // reverse A[i+1] } else reverse(nums, 0); }};
0 0
- [LeetCode]31.Next Permutation
- LeetCode --- 31. Next Permutation
- [Leetcode] 31. Next Permutation
- LeetCode 31.Next Permutation
- [leetcode] 31.Next Permutation
- [leetcode] 31. Next Permutation
- *LeetCode 31. Next Permutation
- Leetcode 31. Next Permutation
- leetcode 31. Next Permutation
- 31. Next Permutation LeetCode
- leetcode 31. Next Permutation
- leetcode 31. Next Permutation
- [LeetCode]31. Next Permutation
- [LeetCode]31. Next Permutation
- LeetCode 31. Next Permutation
- 【leetcode】31. Next Permutation
- LeetCode *** 31. Next Permutation
- leetcode 31. Next Permutation
- 机型判断,写在APPdelegate里面
- @ModelAttribute和@SessionAttributes的用法
- 汇编语言学习第三章-寄存器(内存访问)
- property中的copy属性
- 欢迎使用CSDN-markdown编辑器
- LeetCode 31. Next Permutation
- POI对EXCEL的操作【重点:如何设置CELL格式为文本格式】
- 【光影魔术手】裁剪图片中间部分,再把两头拼接。
- RecyclerView 详解 包含了 单选 多选 动画 嵌套scollview
- 开始我的博客之旅
- UML
- shell脚本程序
- 启动画面和ico等图像大小设置
- 推荐一个学习基础编程技术的网站