继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

leetcode 746号问题和70号问题(动态规划)

落叶灯花
关注TA
已关注
手记 1
粉丝 1
获赞 0

问题:

数组的每个索引做为一个阶梯,第 i个阶梯对应着一个非负数的体力花费值 costi

每当你爬上一个阶梯你都要花费对应的体力花费值,然后你可以选择继续爬一个阶梯或者爬两个阶梯。

您需要找到达到楼层顶部的最低花费。在开始时,你可以选择从索引为 0 或 1 的元素作为初始阶梯。

示例 1:

输入: cost = [10, 15, 20]
输出: 15
解释: 最低花费是从cost[1]开始,然后走两步即可到阶梯顶,一共花费15。
示例 2:

输入: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
输出: 6
解释: 最低花费方式是从cost[0]开始,逐个经过那些1,跳过cost[3],一共花费6。
注意:

cost 的长度将会在 [2, 1000]。
每一个 cost[i] 将会是一个Integer类型,范围为 [0, 999]。

答案:

public static int minCostClimbingStairs(int[] cost) {
    int sum = 0;
    ArrayList<Integer> castArray = new ArrayList<>();
    castArray.add(0);
    for (int i = 0; i < cost.length; i++) {
        castArray.add(cost[i]);
    }

    ArrayList<Integer> outPutArray = new ArrayList<>();
    for (int i = 0; i <= castArray.size(); i++) {
        if (i == 0 || i == 1)
            outPutArray.add(0);
        else {
            int min = Math.min(outPutArray.get(i - 2) + castArray.get(i - 2), outPutArray.get(i - 1) + castArray.get(i - 1));
            outPutArray.add(min);
        }
    }
    sum = outPutArray.get(outPutArray.size() - 1);
    return sum;
}

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。

每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?

注意:给定 n 是一个正整数。

示例 1:

输入: 2输出: 2解释: 有两种方法可以爬到楼顶。
1.  1 阶 + 1 阶
2.  2 阶

示例 2:

输入: 3输出: 3解释: 有三种方法可以爬到楼顶。
1.  1 阶 + 1 阶 + 1 阶
2.  1 阶 + 2 阶
3.  2 阶 + 1 阶

答案:

public static int climbStairs(int n) {
      if (n==1)
          return 1;
      if (n==2)
          return  2;
      return climbStairs(n-1)+climbStairs(n-2);

}
递归写法虽然能算出答案,但是会报错,需要采用非递归写法:
public static int climbStairs(int n) {


    ArrayList<Integer> sum = new ArrayList<>();
    sum.add(0);
    for (int i = 1; i <=n ; i++) {
        if (i==1){
        sum.add(i);
        continue;
        }
        if (i==2) {
            sum.add(i);
            System.out.println("++"+sum.get(1));
        }
        else { System.out.println(sum.get(i - 1));
            sum.add(sum.get(i - 2)+sum.get(i - 1));
        }
    }
    return sum.get(n);
}


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP