<31>——Next Permutation
来源:互联网 发布:免费炒股软件 编辑:程序博客网 时间:2024/06/18 10:21
31、Next Permutation
下一个排列
给定一个整数数组来表示排列,找出其之后的一个排列。
注意事项
排列中可能包含重复的整数
样例
给出排列[1,3,2,3]
,其下一个排列是[1,3,3,2]
给出排列[4,3,2,1]
,其下一个排列是[1,2,3,4]
分析:
下一个排列,即组成下一个比他大的数字,如:
1359
1395
1539
1935
1953
……
则有这三种可能:
1.9531,直接逆序->1359
2.1359,最大的数字升序,->1395,直接和后一位交换即可。
3.1395,中间数的升序,->1539,3和5交换后,3和9还有逆序。
代码:
class Solution {public: void nextPermutation(vector<int>& nums) { int N=nums.size(); int count=-1; for(int i=N-2;i>=0;i--) if(nums[i]<nums[i+1]) { count=i; break; } if(count==-1) { reverse(nums.begin(),nums.end()); return; } int j; for(j=N-1;j>count;j--) if(nums[j]>nums[count]) break; swap(nums[count],nums[j]); reverse(nums.begin()+count+1,nums.end()); }};
阅读全文
0 0
- <31>——Next Permutation
- LeetCode——Next Permutation
- leetcode——Next Permutation
- HomeWork——Next Permutation
- leetcode——Next Permutation
- Algorithms—31.Next Permutation
- leetcode——31——Next Permutation
- 【leetcode】Array—— Next Permutation(31)
- LeetCode 31: Next Permutation
- [leetcode 31] Next Permutation
- LeetCode(31) Next Permutation
- LeetCode---(31) Next Permutation
- 31-m-Next Permutation
- leetcode 31 -- Next Permutation
- leetcode 31: Next Permutation
- Leecode#31 Next Permutation
- LeetCode(31) Next Permutation
- LeetCode-31 Next Permutation
- Qt不同版本对中文字符的处理
- 【拜小白opencv】30-平滑处理3线性滤波之——高斯滤波
- org.springframework.beans.factory.BeanCreationException
- List 接口常用子类及其特点
- Android so库Hook技术
- <31>——Next Permutation
- The Rotation Game UVA
- Find n'th Digit of a Number -- 8 kyu
- 搜索------(一)
- 在一个字符串中,找出最长回文子串
- Kinect sdk 2.0 + Opencv 获取深度图像并保存
- java线程死锁
- ImportError: No module named arcpy
- windows窗体程序的创建