问题描述
0、1、2三个数字的全排列有六种,按照字母序排列如下:
012、021、102、120、201、210
输入一个数n
求0~9十个数的全排列中的第n个(第1个为0123456789)。
输入格式
一行,包含一个整数n
输出格式
一行,包含一组10个数字的全排列
样例输入
1
样例输出
0123456789
数据规模和约定
0 < n <= 10!
思路
其实就是全排列的字典序,在这里介绍一下字典序全排列
字典序如下: [1]
设P是1~n的一个全排列:p=p1p2…pn=p1p2…pj-1pjpj+1…pk-1pkpk+1…pn
1)从排列的右端开始,找出第一个比右边数字小的数字的序号j(j从左端开始计算),即 j=max{i|pi<pi+1}
2)在pj的右边的数字中,找出所有比pj大的数中最小的数字pk,即 k=max{i|pi>pj}(右边的数从右至左是递增的,因此k是所有大于pj的数字中序号最大者)
3)对换pj,pk
4)再将pj+1…pk-1pkpk+1…pn倒转得到排列p’=p1p2…pj-1pjpn…pk+1pkpk-1…pj+1,这就是排列p的下一个排列。
上述内容摘自百度百科
总结一下就是
第一步,先从右至左找到第一个递增二元组,记录下较小的数的下标i(有了下标就有值了)
第二步,从右至左找到比array[i]大的数中最小的数array[j](由于字典序排序的原因,从右找起的第一个比array[i]大的数即为比array[i]大的数中最小的数)
第三步,将array[i]和array[j]交换
第四步,将array[i+1]到array[array.length-1]这区间倒转
即可得出下一个字典序全排列。
代码
import java.io.*;
import java.util.*;
public class Main{
static int n,a1[],a2[],a3[];
static char[] data;
static int length;
public static void main(String[] args) throws Exception{
// 算法概括:从后向前遍历,找出第一个交换点,再按照规则找出第二个交换点,将两者进行交换,
// 对第一个交换点之后的字符进行颠倒操作
data= new char[]{'0','1','2','3','4','5','6','7','8','9'};
length=10;
int n=new Scanner(new BufferedInputStream(System.in)).nextInt()-1;
while(n--!=0) {
nextPermutate();
}
print(data);
}
public static void print(char[] data) {
for(int i=0;i<length;i++)
System.out.print(data[i]);
}
public static boolean nextPermutate() {//找出下一个字典序
int end=length-1;
int swapPoint1=end,swapPoint2=end;
while(swapPoint1>0 && data[swapPoint1]<=data[swapPoint1-1])
//从后往前找第一对相邻的递增数字
//将前一个数称为替换数,下标为替换点即swapPoint1-1
swapPoint1--;
if(swapPoint1==0)
return false;
else {
while(swapPoint2>0&&data[swapPoint2]<=data[swapPoint1-1])
//从后往前找一个比替换数大的最小数,由于排序,只会存在一个最小数
//将该数与替换数交换,将替换数后的序列进行颠倒
swapPoint2--;
swap(data,swapPoint1-1,swapPoint2);
reverse(data,swapPoint1,end);
return true;
}
}
public static void swap(char []data,int swapPoint1,int swapPoint2) {
char temp=data[swapPoint1];
data[swapPoint1]=data[swapPoint2];
data[swapPoint2]=temp;
}
public static void reverse(char []data,int swapPoint1,int swapPoint2) {
for(int i=swapPoint1,j=swapPoint2;i<j;i++,j--) {
swap(data,i,j);
}
}
}