The classic topic in "Sword Pointing Offer", this topic was recently discussed in the group, and I came here to review it.
topic
A frog can jump up 1 or 2 steps at a time. Find the total number of jumps the frog can jump up a n steps.
ideas
Jumping to n steps first can be decomposed into two cases:
- Before jumping to n-1 steps, then jumping 1 more to reach n;
- Jump to n-2 steps before, then jump 2 steps to n;
Therefore, the number of n-level jumps is equal to the sum of these two cases.
which isF(n) = F(n-1) + F(n-2)
Similarly, we can continue to deduce:
F(n-1) = F(n-2) + F(n-3)
F(n-2) = F(n-3) + F(n-4)
...
F(2) = F(1) + F(0)
F(1) = 1
F(0) = 1
It can be seen that this is the Fibonacci sequence, starting from the third number in the sequence, and each number is the sum of the previous two numbers. Then simply F(0) + F(1) = F(2)
start and add up to F(n)
to get the result.
problem solving
Golang
func JumpFloor(n int) int {
a, b := 1, 1
for ; n > 0; n-- {
a, b = b, a + b
}
return a
}
Python version
def jump_floor(n):
a, b = 1, 1
for _ in range(n):
a, b = b, a + b
return a