Next Permutation
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
分析:
详细内容可参考STL源码剖析中关于next_permutation分析部分,下图为简单示意图,可辅助理解
简单分析——先验知识
1、reverse_iterator测试
#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;
int main()
{
vector<int> A({1, 2, 3, 4});
for(int i=0; i<A.size(); i++)
cout << A[i];
cout << endl;
auto rfirst = vector<int>::reverse_iterator(A.end());
auto rlast = vector<int>::reverse_iterator(A.begin());
cout << *rfirst << endl;
cout << *rlast;
}
2、查找元素值大于10的元素的个数
int res
= count_if(coll.begin(), coll.end(), bind1st(less<int>(), 10));
3、查找第一个比 3 大的数值 , 下面的代码的意思是找到第一个 3 比取出的数值大的数的位置。bind1st 表示要绑定一个函数,绑定一个函数, greater<int>(),3 ,表示比三大的数。
auto ifind
= find_if(mylist.begin(), mylist.end (), bind1st( greater<int>(), 3));
//方法一:调用next_permutation函数 class Solution { public: void nextPermutation(vector<int>& nums) { next_permutation(nums.begin(), nums.end()); } };
//方法二:自己写一个next_permutation函数 class Solution { public: void nextPermutation(vector<int>& nums) { next_permutationUtil(nums.begin(), nums.end()); } template <typename T> bool next_permutationUtil(T first, T last) //如果要输出全排列,则首先要排序为递增序列 { auto rfirst = reverse_iterator<T>(last); auto rlast = reverse_iterator<T>(first); auto point = next(rfirst); while(point != rlast && *point >= *prev(point)) //存在递增序列对 point++; if(point == rlast) //结束标志,整个序列已经是递减序列 { reverse(rfirst, rlast); return false; } auto change = find_if(rfirst, point, bind1st(less<int>(), *point)); //找到第一个比*point大的值 swap(*point, *change); reverse(rfirst, point); //The range used is [first,last) return true; } };
原文地址:http://blog.csdn.net/keyyuanxin/article/details/46581187