LintCode Climbing Stairs

时间:2023-03-09 02:32:34
LintCode 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?

Example

Given an example n=3 , 1+1+1=2+1=1+2=3

return 3

For the problem, try to think about it in this way.

Firstly, we define the problem of DP(n) as the ways of approaching to n stairs.

The problem of DP(n) depends on DP(n-1) and DP(n-2). Then the DP(n) = DP(n-1) + DP(n-2). Because there is two possibilities for DP(n) happen due to the rule that either it is accomplished by step 1 or step 2 stairs before approaching to n.

Initialize the DP(0) =1 and DP(1) = 1.

Solve problem DP(n)

 public class Solution {
/**
* @param n: An integer
* @return: An integer
*/
public int climbStairs(int n) {
// write your code here
if (n <= 1) {
return 1;
}
int last = 1, lastlast = 1;
int now = 0;
for (int i = 1; i < n; i++) {
now = last + lastlast;
lastlast = last;
last = now;
}
return now;
}
}

Then this problem is a fibonacci sequence