JS面试题-算法台阶问题

有100格台阶,可以跨1步可以跨2步,那么一个有多少种走法;

今天电话面试。遇到一道算法问题,然后瞬间一脸懵逼;

然后机智的我,自作聪明的想到如果一个人每次都走1步,那么最多100步,每次走2步最少50步;然后明显跑题了。。。还好对方及时把我打断了。。。不然我估计要对着这玩意一直死脑经。。。一路走到黑。。

 

然后回到家了。拿着偶的mac,然后静静的思考,终于写出来了

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种

只有2格的时候,可以1+1||2.。。。2

3格的时候,1+1+1||2+1||1+2.。。3

4格的时候1+1+1+1||2+2||2+1+1||1+1+2||1+2+1。。。5

sn = s(n-1)+s(n-2)

 


斐波那契算法...然后就可以用

for(i=2;i<this.total;i++){
     res = this.n1 + this.n2;
     this.n1 = this.n2;
     this.n2 = res;
}

 

 

 

可能本人对算法不是特别在行~如果有异议欢迎指正

 

posted @ 2016-07-25 20:42  一点点白  阅读(2671)  评论(4编辑  收藏  举报