Problem 24 :Lexicographic permutations
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?
思路 :
整个解题的思路就是这个公式,这就是一个全排列的问题,树状图可以很好的描述这个过程,就拿题中那个举例子:
总的排列方式
好像一下子回到了高中,数学老师在讲台上讲排列组合还历历在目,哈哈哈!
我的思路就是给写一个for回圈,从最小的数开始----0123456789,最大的数-----9876543210结束,如果排列数满足条件,
怎么设置是否满足条件呢?我的灵感是从犹太人抄写圣经检查误差的方法得来的,这是以前一本书中的读到的(有兴趣的可以去了解一下,犹太人如何对圣经抄写本查错)所以说多读读书没错,三毛说过,你读过的书不是过眼云烟,而是潜藏在你的气质中,谈吐中,在胸襟的无涯中!
言归正传,若满足条件,就累加一次,若累加达到100万,则跳出循环,最后一个数即为结果!然而这样做起来算得太慢了,有点像电动机过载,小马拉大车,效率太低了。我觉得是范围界定得太大了,于是我便考虑缩小范围,具体的方法是这样的。
这个图就是循环初值为什么设成代码中那样的原因!
代码 :
clear,clc
tic
k = 1008000;
A = '0123456789';
for i = 2798654310:-1:0123456789
B = num2str(i);
len = length(B);
if len < length(A)
for i = 1:len
C(i+1) = char(B(i));
end
C(1) = '0';
len = len + 1;
else
for i = 1:len
C(i) = char(B(i));
end
end
c = sort(C);
if c == A
disp(C);
k = k - 1;
end
if k < 1000000
break
end
end
toc
结果 :2783915460
运行出来是这样的:
希望大家多多交流!