您的位置:首页 > 编程语言 > Java开发

Java 欧拉工程 第二十四篇【0,1,2,3,4,5,6,7,8,9的第100万个字典排列是什么】

2014-08-24 17:29 246 查看
题目:排列是一个物体的有序安排。例如3124是1,2,3,4的一种排列。如果所有的排列按照数值或者字母序排序,我们称其为一个字典序。0,1,2的字典排列有:

012 021 102 120 201 210

0, 1, 2, 3, 4, 5, 6, 7, 8,9的第100万个字典排列是什么?

原题:
A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically,
we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:

012 021 102 120 201 210
What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
解题思路:由题意,3位数的字典排列共有6种,不难看出n位数的字典排列应有n!个,由字典排序的规律可知,0-9的排列除去第一位数,剩下的排列数量可表示位9!
9!=362880,所以我们要求的第 1 000 000数列应在第2个9!和第3个9!之间,即可以确定第一位数一定为2,而1 000 000-9!-9!=274240,除去确定的第一位数2,剩下的9位数的第274240个排列为我们所求,同理274240在第6个8!和第7个8!之间,舍弃了2之后, 0,1,3,4,5,6,7所以第二位数一定为7,依次类推,换算成公式可表示为
m+(a)n!>1000000(m>=0,a>=0,n<-[0,9]),a即是我们需确定的值的位置,需注意在一位数确认时,在之后的排序中需要舍去。如下贴上java的代码:
public class Launcher {
public static void main(String[] args) {
Vector<Integer> list= new Vector<Integer>();
Vector<Integer> numList= new Vector<Integer>();
int sum=0;
for(int i=0;i<10;i++){
list.add(i);
}
for(int j=9;j>=0;j--){
for(int n=1;n<12;n++){
if(sum+n*jiecheng(j)>1000000){
numList.add(list.get(n-1));
list.remove(n-1);
sum+=(n-1)*jiecheng(j);
break;
}
}
}

System.out.println(numList);
}

public static int jiecheng(int n){
int sum=1;
for(int i=1;i<=n;i++){
sum*=i;
}
return sum;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: