NOTE

Jump Floor

Use the Fibonacci recurrence to calculate the number of ways a frog can climb the stairs.

Data Structures & AlgorithmsCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Problem Description

A frog can jump either 1 step or 2 steps at a time. Find the total number of ways the frog can jump up a staircase with n steps (different orders count as different results).

2. Approach

  • It is essentially the Fibonacci sequence

3. Implementation

// It is essentially the Fibonacci sequence
// Time complexity: O(n)
// Space complexity: O(1)
func JumpFloor(number int) int {
	if number <= 2 {
		return number
	}

	a := 1
	b := 2
	res := a + b
	for i := 3; i < number; i++ {
		a = b
		b = res
		res = a + b
	}

	return res
}

4. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub