【C++】函数next_permutation
学习算法时发现可以使用next_permutation函数来替代手写起到一个全排序的作用。
函数原型
函数定义在<algorithm>头文件中,用于生成给定序列的下一个字典序排列(如果不理解该概念先学习一下字典序的概念)
bool next_permutation( BidirectionalIterator first, BidirectionalIterator last );
参数
- first: 指向序列起始位置的双向迭代器。
- last: 指向序列结束位置的双向迭代器(不包含在序列中)。
返回值
- 如果成功生成下一个排列,返回 true。
- 如果当前序列已经是字典序中的最大排列(即降序排列),则返回false,并将序列重新排列为升序。
示例
使用next_permutation进行全排列并输出结果
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> nums = {1, 2, 3};
sort(nums.begin(), nums.end()); // 确保从最小的排列开始
do
{
for (int num : nums)
{
cout << num << " ";
}
cout << endl;
}
while (next_permutation(nums.begin(), nums.end()));
return 0;
}
输出:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
原理
- 从右向左找到第一个升序对 (i, i+1),即 nums[i] < nums[i+1]。
- 再次从右向左找到第一个大于 nums[i] 的元素 nums[j]。
- 交换 nums[i] 和 nums[j]。
- 反转 i+1 到末尾的子序列。(为了将降序子序列变为升序子序列,从而确保生成的排列是字典序中的下一个排列)