70. 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?

 

Subscribe to see which companies asked this question

Hide Tags
  Dynamic Programming
 
Solution 1:
public class Solution {
    public int climbStairs(int n) {
        if(n <=2 )
            return n;
        
        int[] count = new int[n];
        count[0] = 1;
        count[1] = 2;
        
        return getCount(count, n-1);
    }
    
    private int getCount(int[] count, int index)
    {
        if(count[index] != 0)
            return count[index];
        int steps = getCount(count, index -1) + getCount(count, index -2);
        count[index] = steps;
        return steps;
    }
}

 

 

Solution 2:

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

 

 

 

转载于:https://www.cnblogs.com/neweracoding/p/5390795.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值