zoukankan      html  css  js  c++  java
  • <Dynamic Programming> 120 279

    120. Triangle

    从倒数第二行找,然后逐个遍历这个DP数组,对于每个数字,和它之后的元素比较选择较小的再加上面一行相邻位置的元素做为新的元素,然后一层一层的向上扫描

    class Solution {
        public int minimumTotal(List<List<Integer>> triangle) {
            if(triangle.size() == 0 || triangle == null) return 0;
            int rows = triangle.size();
            int[] dp = new int[rows + 1];
            for(int i = rows - 1; i >= 0 ; i--){
                for(int j = 0; j <= i; j++){
                    dp[j] = Math.min(dp[j], dp[j + 1]) + triangle.get(i).get(j);
                }    
            }
            return dp[0];
        }
    }

    279. Perfect Squares

    class Solution {
        public int numSquares(int n) {
            int[] dp = new int[n + 1];
            Arrays.fill(dp, Integer.MAX_VALUE);
            dp[0] = 0;
            for(int i = 1; i <= n; i++){
                for(int j = 1; j * j <= i; j++){
                    dp[i] = Math.min(dp[i], dp[i - j * j] + 1);
                }
            }
            return dp[n];
        }
    }
  • 相关阅读:
    功能规格说明书
    绝望的作业
    php闭包
    php isset emtpy
    PHP超级全局变量、魔术变量和魔术函数
    死锁的一个例子
    php session cookie
    http状态码301、302
    php浮点数
    学过的设计模式
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/11914378.html
Copyright © 2011-2022 走看看