备忘
/*
date:
2018/3/8 10:53
des:
2.1.12 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
analyze:
先看一下题目,permutation(排列)给出一个数列,输出下一个全排列比当前数列大的最小的排列,如果当前是最大就输出最小的那个.
不分配额外的空间
那么问题来了如何生成全排列
*/
#include "type.h"
int arr_permutation[] = {1,2,3,4};
int arr_count = sizeof(arr_permutation)/sizeof(int);
vectorInt nums_permutation(arr_permutation,arr_permutation+arr_count);
template<typename InIt>
void Print(InIt begin,InIt end)
{
while(begin!=end)
{
printf("[%d]",*begin);
begin++;
}
printf("\n");
}
//打印全排列 递归实现
template<typename Source,typename SourceIt>
void permunationGenerationRecursion(Source &nums, SourceIt begin, SourceIt end)
{
//Print(begin,end);
if (begin==end)
{
Print(nums.begin(),nums.end());
return;
}
for (SourceIt it=begin; it!=end; it++)
{
swap(*it,*begin);//a{} 交换a
permunationGenerationRecursion(nums,begin+1,end);
swap(*it,*begin);//将数组恢复
}
}
//非递归实现
void permunationGeneration(vectorInt &nums)
{
sort(nums.begin(),nums.end());//先排序
while(true)
{
int index = 0;
for(int j=nums.size()-1; j!=0; j--)
{
if (nums[j]>nums[j-1])
{
//存在下一个排列
index = j-1;
break;
}
}
if (index<0)
{
return;//已经输出全部排列
}
//寻找交换的位置
for (int i=nums.size()-1; i!=index; i--)
{
if (nums[i]>nums[index])
{
swap(nums[i],nums[index]);
reverse(nums.begin()+index+1,nums.end());
Print(nums.begin(),nums.end());//输出
break;
}
}
}
}
int nextPermunation(vectorInt&nums)
{
vectorInt::reverse_iterator rightIt = nums.rbegin();
vectorInt::iterator beginIt = nums.begin();
int minValue = 0;
while((rightIt+1) != nums.rend())
{
int nextVal = *(rightIt+1);
if (nextVal<*rightIt)
break;
rightIt++;
}
if ((rightIt+1) == nums.rend())
{
reverse(nums.begin(),nums.end());
}
else
{
vectorInt::reverse_iterator it = nums.rbegin();
while(it != rightIt+1)
{
if (*it>*(rightIt+1))
{
swap(*it,*(rightIt+1));
reverse(nums.rbegin(),rightIt+1);
break;
}
it++;
}
}
return 0;
}