Question
from lintcode
You are climbing a staircase. It takes n steps to reach 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
Ideas
see code comments;
/**
* Formula:
* number of paths to arrive Xth stair =
* number of paths to arrive X - 1 th stair
* +
* number of paths to arrive X - 2 th stair
*
* That is:
* f(x) = f(x - 1) + f(x - 2)
*
* You need to remember 2 states: x - 1 and x - 2 cases.
*
*/
public class Solution {
private int numOfStates = 2;
private int indexOf(int n) {
return n % numOfStates;
}
/**
* @param n: An integer
* @return: An integer
*/
public int climbStairs(int n) {
/**
* edge case
*/
if (n == 0) return 0;
int[] total = new int[numOfStates];
/**
* Initial states
*/
total[indexOf(1)] = 1;
total[indexOf(2)] = 2;
/**
* calculation: f(x) = f(x - 1) + f(x - 2)
*/
for(int x = 3; x <= n; x++)
total[indexOf(x)] =
total[indexOf(x - 1)] + total[indexOf(x - 2)];
// calculated result after dynamic programming
return total[indexOf(n)];
}
}
网友评论