其他分享
首页 > 其他分享> > LeetCode - climbing-stairs

LeetCode - 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?

 

题意:

你正在爬楼梯。到达山顶需要n步。

每次你可以爬1或2级台阶。你可以用几种不同的方式爬到山顶?

 

解题思路:

仔细一看,这题就是斐波那契数列的求法,但是这里需要用动态规划来解决

 

动态规划首先确定 是维护一个一维数组

然后确定边界,这里的边界和斐波那契数列差不多,dp[0] =1,dp[1] =1

最后是找递推公式

dp2] = dp[0]+dp[1]  { (1,1),(2)}

dp[3] = dp[2]+dp[1] {(1,1,1),(1,1,2),(2,1)}

...

就是在之前的基础上,后面再加上1或2进行组合

 

下面给出Java代码:

public static  int climbStairs(int n) {
		
        if(n == 0) {
        	return 0;
        }
        
        int[] dp = new int[n+1];       
        dp[0] = 1;
        dp[1] = 1;
        
        for(int i = 2;i <= n;i++) {
        	dp[i] = dp[i-2] + dp[i-1];
        }
        return dp[n];
    }

 

标签:int,top,steps,climbing,那契,stairs,LeetCode,dp
来源: https://blog.csdn.net/toward_south/article/details/89789903