zoukankan      html  css  js  c++  java
  • leetcode Triangle

    
    

    分析:从最小面一层开始往上计算,设dp[i][j]是以第i层j个元素为起点的最小路径和,动态规划方程如下

    
    

    dp[i][j] = value[i][j] + max{dp[i-1][j], dp[i-1][j+1]}

    
    

    因为每一层之和它下一层的值有关,因此只需要一个一位数组保存下层的值,



    public
    int minmumTotalDP(ArrayList<ArrayList<Integer>> triangle){ int rows=triangle.size(); int[] dp=new int[rows]; //初始化值、、动态规划 for(int i=0;i<rows;i++){ dp[i]=triangle.get(rows-1).get(i); } for(int i=rows-2;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]; }
     private int minValue ;
        public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
            if (triangle == null) {
                return 0;
            }
            minValue= Integer.MAX_VALUE;
            int n = triangle.size();
            Stack<Integer> stack = new Stack<Integer>();
            stack.push(0);
            getResult(triangle, stack, 1, n, triangle.get(0).get(0));
            return minValue;
        }
        private void getResult(ArrayList<ArrayList<Integer>> triangle,
                Stack<Integer> stack, int index, int n, int sum) {
            // TODO Auto-generated method stub
            if (index == n) {
                if (sum < minValue) {
                    minValue = sum;
                }
                stack.pop();
                return;
            }
            int left = stack.peek();
            stack.push(left);
            getResult(triangle, stack, index + 1, n,
                    sum + triangle.get(index).get(left));
            int right = stack.peek() + 1;
            stack.push(right);
            getResult(triangle, stack, index + 1, n,
                    sum + triangle.get(index).get(right));
            stack.pop();
        }
  • 相关阅读:
    misc子系统
    Spring boot+RabbitMQ环境
    Linux input
    lnmp环境的搭建
    DDD的.NET开发框架
    【踩坑记】从HybridApp到ReactNative
    Migrating from IntelliJ Projects
    Windows下Redis中RedisQFork位置调整
    远程仓库版本回退方法 good
    maven repository
  • 原文地址:https://www.cnblogs.com/csxf/p/3736505.html
Copyright © 2011-2022 走看看