【STL】next_permutation的实现
来源:互联网 发布:linux cmdline 编辑:程序博客网 时间:2024/06/10 07:28
一、使用字典序法
首先,从最尾端开始寻找两个相邻的元素,令第一个元素为*i, 第二个元素为*ii, 且满足 *i < *ii(其中pos[*i] < pos[*ii], pos代表下标)。找到这样一组相邻的元素之后,再从最尾端开始往前检验,找出第一个大于*i的元素,令为 *j, 将i, j,元素对调,再将ii之后的所有元素颠倒顺序,即可求出“下一个”排列组合。
以下解法为题目: leetcode next permutation
class Solution {public: void nextPermutation(vector<int>& nums) { int len = nums.size(); // 只有只一个元素或为空 if(len < 2) return; // 如果当前元素已经是最大排列时,下一个则是最小排列 bool flag = false; for(int i = 0; i < len-1; ++ i) { if(nums[i] < nums[i+1]) { flag = true; break; } } if(!flag) { reverse(nums.begin(), nums.end()); return; } // 找到从最尾端开始的满足*i < *ii的相邻元素 int posx = len-2, posy = len-1; for(int i = len-2; i >= 0; i --) { if(nums[i] < nums[i+1]) { posx = i; posy = i + 1; break; } } // 从最尾端开始找到第一个大于 *i 的元素,并与之对调 for(int i = len - 1; i >= 0; -- i) { if(nums[i] > nums[posx]) { swap(nums[posx], nums[i]); break; } } // 反转ii之后的所有元素 reverse(nums.begin() + posy, nums.end()); }};
二、康托逆展开
对于给定一个n和一个k,求由1-n组成的第k大排列以下解法的题目来源:leetcode permutation sequence
class Solution {public: int fac(int n) { int ans = 1; for(int i = 1; i <= n; ++ i) ans *= i; return ans; } string getPermutation(int n, int k) { // 获取当前(n-1)! int cnt = fac(n - 1); // 组成排列的所有元素 vector<int> permutation; for(int i = 1; i <= n; ++ i) permutation.push_back(i); string ans = ""; for(int i = n; i >= 1; i --) { // idx 为右边比当前i小的元素个数 int idx = (k-1) / cnt; // 置当前元素 ans += to_string(permutation[idx]); // 去除当前元素以避免产生重复数 permutation.erase(permutation.begin() + idx); // 获取当前剩下的第k大排列 k = k - idx * cnt; // 防止 n = 1 的情况,除0异常 if(i > 1) cnt /= (i-1); } return ans; }};已知一个排列,可以用康托展开求其序数。假设排列为,这个排列对应的序数为。其中表示位于第i位右边比小的元素的个数,.
上述过程即为康托展开的过程,而给出的代码为逆康托展开
参考:
ww32cc的博客
侯捷, STL源码剖析
0 0
- 【STL】next_permutation的实现
- C++ STL next_permutation的实现原理
- C++ STL next_permutation的实现原理
- C++ STL中next_permutation的实现
- C++STL的next_permutation
- 使用stl的next_permutation
- C++STL的next_permutation
- C++STL的next_permutation
- STL的next_permutation函数
- STL实现全排列 next_permutation
- 用STL的next_permutation算法实现全排列
- stl next_permutation的全排列原理及实现样例
- STL算法之 next_permutation、prev_permutation 的原理和实现
- STL的排列算法next_permutation
- 详解STL中next_permutation()函数实现
- 如何实现STL中的next_permutation函数?
- STL next_permutation
- 【STL】next_permutation
- 利用广播机制(BroadcastReceiver)窃听短信
- 黑马程序员-C语言-小知识点集
- Wait Sets and Notification(java语言规范17.2章节)
- [leetcode] 154. Find Minimum in Rotated Sorted Array II 解题报告
- Hibernate配置文件
- 【STL】next_permutation的实现
- caffe源码阅读——Blob类
- tomcat启动一闪而过
- 记一次花费一天时间debug的过程
- java广度优先遍历
- bzoj3926 广义后缀自动机
- Collection Data Structures In Swift
- Valid Palindrome
- 多线程 工厂 > 商店(仓库) > 客户模式 消费者模式 实现多仓库 多产品 多工厂 多客户