JS Interview Question About the Algorithm Step

  • 2021-07-06 09:46:13
  • OfStack

There are 100 steps, which can span 1 step and 2 steps, so how many kinds of walking methods are there for one;

Telephone interview today. Encountered an algorithm problem, and then instantly forced a face;

Then witty me, smart thought that if a person takes 1 step every time, then the maximum is 100 steps, and the minimum is 50 steps at 2 steps every time; Then it was obviously beside the point. . . Fortunately, the other party interrupted me in time. . . Otherwise, I guess I'll have to go straight to this thing. . . Road 1 goes to the black. .

And then I went home. Take my mac, then think quietly, and finally write it out


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)

When it's only one grid. You can only take one step. . . . Just one

When there are only 2 squares, it can be 1 +12.. . . 2 species

In 3 squares, 1 +1 +12 +11 +2.. . 3 species

1 +1 +1 +12 +22 +1 +11 +1 +21 +2 +1 in 4 squares. . . 5 species

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

Fibonacci algorithm... and then you can use


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

Maybe I am not particularly good at the algorithm ~ If there is any objection, please correct me


Related articles: