[Leetcode] [Java] Climbing Stairs__java

Source: Internet
Author: User
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];
    }


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.