[dp]leetcode 746. Min Cost Climbing Stairs

输入:一个数组cost,cost[i]表示越过第i个台阶的代价(可能是热量,也可能是过路费)
输出:走过这n个台阶,需要的最小代价
规则:一旦你为第i个台阶付出代价cost[i],那么你可以到达第i+1个台阶,也可以到达第i+2个台阶。你可以从第0个或者第1个台阶开始走。
分析:没什么好说的,一步步走,没走一步付出代价private void walk(int step,int currentcost) 表达站在第i个台阶,付出了多少代价。
你可以试着把cache去掉,当然是超时。加cache是因为,如果你曾经花费代价10站在了第5个台阶,那下次遇到需要花费代价15站在了第5个台阶,就没必要进行走下去。因为代价肯定高嘛。

class Solution {
    private int mincost = Integer.MAX_VALUE;
    private int[] cost;
    private int[] cache;
    private int n;
    public int minCostClimbingStairs(int[] cost) {
        this.cost = cost;
        this.n = cost.length;
        this.cache = new int[n];
        walk(0,0);
        walk(1,0);
        return mincost;
    }
    private void walk(int step,int currentcost){
        if(step>=n){
            mincost = Math.min(mincost,currentcost);
            return;
        }
        if(cache[step]==0 || currentcost<cache[step]){
             cache[step] = currentcost;
             walk(step+1,currentcost+cost[step]);
             walk(step+2,currentcost+cost[step]);
        }
       
    }
}

动态规划分析:初步分析得到能站点第i个台阶的代价应该是与第i-1和第i-2台阶有关。
之前很多从回溯法到动态规划都会发现dp[i]和回调函数的含义会有点变化。这次不会发生变化,直接拿过来。

dp[i]表示能够到达第i个台阶需要的最小代价
dp[i]=min(dp[i-1]+cost[i-1],dp[i-2]cost[i-2]])
最后返回dp[n]
 	public int minCostClimbingStairs(int[] cost) {
        int n = cost.length;
        int[] dp = new int[n+1];
        dp[0] = 0;
        dp[1] = 0;
        for(int i=2;i<=n;i++){
            dp[i] = Math.min(dp[i-2]+cost[i-2],dp[i-1]+cost[i-1]);
        }
        return dp[n];
    }
发布了148 篇原创文章 · 获赞 35 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/flying_all/article/details/103336185