今天電話面試。遇到一道算法問題,而後瞬間一臉懵逼;面試
而後機智的我,自做聰明的想到若是一我的每次都走1步,那麼最多100步,每次走2步最少50步;而後明顯跑題了。。。還好對方及時把我打斷了。。。否則我估計要對着這玩意一直死腦經。。。一路走到黑。。算法
而後回到家了。拿着偶的mac,而後靜靜的思考,終於寫出來了this
var Stairs = new step(); function step(){ this.n1=1; this.n2=2; this.total=100; this.getFunction = getFunction; } function getFunction(){ for(i=2;i<this.total;i++){ res = this.n1 + this.n2; this.n1 = this.n2; this.n2 = res; } return res; } var totalStairs = Stairs.getFunction(); alert(totalStairs)
只有1格的時候。只能走1步。。。。就1種spa
只有2格的時候,能夠1+1||2.。。。2種code
3格的時候,1+1+1||2+1||1+2.。。3種blog
4格的時候1+1+1+1||2+2||2+1+1||1+1+2||1+2+1。。。5種get
sn = s(n-1)+s(n-2)io
斐波那契算法...而後就能夠用function
for(i=2;i<this.total;i++){ res = this.n1 + this.n2; this.n1 = this.n2; this.n2 = res; }
可能本人對算法不是特別在行~若是有異議歡迎指正class