Climbing Stairs

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

 

This problem is actually a Fibonacci problem. The intuition to solve this problem is, the way to N steps stair is the sum of the way to N-1 and N-2 steps stairs.

  • 1, From N - 1 steps to N, there is only one way to take 1 step to get to N
  • 2, From N - 2 steps to N, there is only one way to take a 2 steps to get to N
  • 3, Also, there is no overlapping between the above 2 ways
  • 4, So, the way to get to N steps stair is the sum of N - 1 and N - 2

Code is Simple 

public int climbStairs(int n) {
if (n <= 0) return 0;
if (n == 1) return 1;
if (n == 2) return 2;
int s1 = 1;
int s2 = 2;
int result = 0;
for(int i = 2; i < n; i++){
result = s1 + s2;
s1 = s2;
s2 = result;
}
return result;
}

 

你可能感兴趣的:(bing)