topic:
You are are climbing a stair case. It takes n steps to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can your climb to the top? The following:
Suppose you climb a ladder, you need to run to the top n steps.
You can only climb 1 or 2 paces at a time. Finally how many different ways you can climb to the top.
Algorithm Analysis:
The problem of climbing a ladder is essentially the Fibonacci sequence:
* When N=1, Ways=1
* When n=2, there are [2] [1,1] two situations, ways=2
* When n=3, there are [1,1,1] [1,2] [2,1] Three of cases, ways=3
* When n=4, there are [1,1,1,1] [2,2] [1,1,2] [1,2,1] [2,1,1] five situations, ways=5
* When n=5, there are [1,1,1,1,1] [2,2,1] [2,1,2] [1,2,2] [1,1,1,2] [1,1,2,1] [1,2,1,1] [2,1,1,1] Eight of cases, ways=8
* When N>3, n corresponds to the number of n-1 and n-2 of the sum. At this point, the law coincides with the regularity of the Fibonacci sequence.
* The Fibonacci sequence is such a sequence: 1, 1, 2, 3, 5, 8, 13, 、...... Mathematically, it is defined in a recursive way: F0=0,f1=1,fn=f (n-1) +f (n-2) (n>=2)
The code is as follows:
public class Solution
{
///==+
/*public int climbstairs (int n)
{
int res = 0;
if (n==0) res= 0;
if (n==1) res= 1;
if (n==2) res= 2;
if (n>2) res= climbstairs (n-1) +climbstairs (n-2);
return res;
} ///
/use array public
int climbstairs (int n)
{
int res[] = new int[n+1];
int i=0;
for (i=0;i<n+1;i++)
{
if (i==0) res[i]= 0;
if (i==1) res[i]= 1;
if (i==2) res[i]= 2;
if (i>2)
res[i]=res[i-1]+res[i-2];
}
return res[n];
}