zoukankan      html  css  js  c++  java
  • [LeetCode]: 64: Minimum Path Sum

    题目:

    Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

    Note: You can only move either down or right at any point in time.

    思路:动态规划

    整个序列的最小路径= 上一个节点的最小路径+当前路径的节点值

    依次往前看,第一个点的最小序列等于其本身

    代码:

        public int minPathSum(int[][] grid) {
    
            if(grid.length == 0){
                return 0;
            }
            
            int[][] intResult = new int[grid.length][grid[0].length];
    
            for(int i = 0;i<grid.length;i++){
                for(int j = 0;j<grid[i].length;j++){
                    if(i==0 && j==0){
                        intResult[i][j] = grid[i][j];
                    }else if(i == 0 && j!=0){
                        intResult[i][j] = intResult[i][j-1] + grid[i][j];
                    }
                    else if(j== 0 && i!= 0){
                        intResult[i][j] = intResult[i-1][j] + grid[i][j];
                    }
                    else{
                        int intX = intResult[i][j-1] + grid[i][j];
                        int intY = intResult[i-1][j] + grid[i][j];
                        
                        if(intX > intY){
                            intResult[i][j] = intY;
                        }
                        else{
                            intResult[i][j] = intX;
                        }
                    }
                }
            }
            
            return intResult[grid.length-1][grid[0].length-1];
        }
  • 相关阅读:
    混合背包
    二维背包
    0/1背包问题(DP)
    冒泡排序
    快速排序
    最长上升子序列
    二分查找
    n后问题
    crontab 定时任务
    删除以某字符串开头的表
  • 原文地址:https://www.cnblogs.com/savageclc26/p/4878166.html
Copyright © 2011-2022 走看看