zoukankan      html  css  js  c++  java
  • [leetcode]64Minimum 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 class Q64MinimumPathSum {
        public static void main(String[] args) {
    
        }
        public int minPathSum(int[][] grid) {
            int m = grid.length;
            int n = grid[0].length;
            //求出最左边一行的每个点对应的最小和
            for (int i = 1; i < m; i++) {
                grid[i][0] += grid[i-1][0];
            }
            //最上边行的
            for (int i = 1; i < n; i++) {
                grid[0][i] += grid[0][i-1];
            }
            //前两个是判断特殊情况
            if (m == 1)
                return grid[0][n-1];
            else if (n == 1)
                return grid[m-1][0];
            //动态规划主体
            else
            {
                int temp;
                for (int i = 1; i < m; i++) {
                    for (int j = 1; j < n; j++) {
                        //求该点的最小和
                        temp = Math.min(grid[i-1][j],grid[i][j-1]);
                        grid[i][j] += temp;
                    }
                }
                //右下角的点
                return grid[m-1][n-1];
            }
        }
    }
  • 相关阅读:
    Asp.Net.Core 系列-中间件和依赖注入Hosting篇
    Asp.Net.Core 系列-中间件和依赖注入进阶篇
    Asp.Net.Core 系列-中间件和依赖注入基础篇
    修饰符总结
    CSS3边框border知识点
    浅谈CSS中的居中
    c#中的委托和事件
    c#基础知识复习-static
    c#基础知识复习
    Bfc的理解
  • 原文地址:https://www.cnblogs.com/stAr-1/p/7251199.html
Copyright © 2011-2022 走看看