今天电话面试。遇到一道算法问题,而后瞬间一脸懵逼;面试
而后机智的我,自做聪明的想到若是一我的每次都走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