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?


分析,该问题类似于斐波那契序列问题,直观上采用递归来做,f(n)=f(n-1)+f(m-2),然而时间复杂度太大,因此类似问题可以采用动态规划的思想,如下代码


public class Solution {

   

    

    public int climbStairs(int n) {

        if(n<=2)

            return n;

        else

        {

            int[] kinds=new int[n];

            kinds[0]=1;

            kinds[1]=2;

            for(int i=2;i<n;i++)

            {

                kinds[i]=kinds[i-1]+kinds[i-2];

            }

            return kinds[n-1];

        }

    }

}