2018-12-11 15:57:58 +08:00
|
|
|
/* mbinary
|
|
|
|
#########################################################################
|
2018-12-29 19:30:21 +08:00
|
|
|
# File : permute_next_permutation.c
|
2018-12-11 15:57:58 +08:00
|
|
|
# Author: mbinary
|
|
|
|
# Mail: zhuheqin1@gmail.com
|
2019-01-31 12:09:46 +08:00
|
|
|
# Blog: https://mbinary.xyz
|
2018-12-11 15:57:58 +08:00
|
|
|
# Github: https://github.com/mbinary
|
|
|
|
# Created Time: 2018-11-17 14:31
|
2018-12-29 19:30:21 +08:00
|
|
|
# Description: support duplicate values.
|
|
|
|
eg [1,1,5] nextPermutation [1,5,1]
|
2018-12-11 15:57:58 +08:00
|
|
|
#########################################################################
|
|
|
|
*/
|
2018-11-07 16:52:55 +08:00
|
|
|
#include<stdio.h>
|
|
|
|
|
|
|
|
void swap(int*arr,int i,int j)
|
|
|
|
{
|
|
|
|
int tmp;
|
|
|
|
tmp = arr[i];
|
|
|
|
arr[i] = arr[j];
|
|
|
|
arr[j] = tmp;
|
|
|
|
}
|
2018-12-29 19:30:21 +08:00
|
|
|
void reverse(int *arr,int i,int j)
|
2018-11-07 16:52:55 +08:00
|
|
|
{
|
2018-12-29 19:30:21 +08:00
|
|
|
while (i<j)swap(arr,i++,j--);
|
|
|
|
}
|
|
|
|
void nextPermutation(int *arr,int n)
|
|
|
|
{
|
|
|
|
if(n>1){
|
2018-11-07 16:52:55 +08:00
|
|
|
int i;
|
|
|
|
for(i=n-1;i>0;--i){
|
|
|
|
if(arr[i]>arr[i-1])break;
|
|
|
|
}
|
2018-12-29 19:30:21 +08:00
|
|
|
i-=1;
|
|
|
|
if(i>=0){
|
|
|
|
for(int j=n-1;j>i;j--){
|
|
|
|
if(arr[j]>arr[i]){
|
|
|
|
swap(arr,j,i);
|
|
|
|
break;
|
|
|
|
}
|
2018-11-07 16:52:55 +08:00
|
|
|
}
|
|
|
|
}
|
2018-12-29 19:30:21 +08:00
|
|
|
reverse(arr,i+1,n-1);
|
2018-11-07 16:52:55 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void printArr(int *arr,int n)
|
|
|
|
{
|
|
|
|
for(int i=0;i<n;++i)printf("%d ",arr[i]);
|
|
|
|
printf("\n");
|
|
|
|
}
|
|
|
|
int main()
|
|
|
|
{
|
|
|
|
int n = 4;
|
|
|
|
int a[n];
|
|
|
|
for(int i=0;i<n;++i)a[i]=i;
|
|
|
|
long long int fac=1;
|
|
|
|
for(int i=2;i<=n;++i)fac*=i;
|
|
|
|
for(int i=0;i<fac;++i){
|
|
|
|
printf("rank %d :",i);
|
|
|
|
printArr(a,n);
|
2018-12-29 19:30:21 +08:00
|
|
|
nextPermutation(a,n);
|
2018-11-07 16:52:55 +08:00
|
|
|
}
|
|
|
|
}
|