日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

63. Unique Paths II and 64. Minimum Path Sum

發布時間:2023/12/10 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 63. Unique Paths II and 64. Minimum Path Sum 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

  • 1 63 Unique Paths II
    • 1.1 題目描述
    • 1.2 動態規劃解決
  • 2 64. Minimum Path Sum
  • 2.1 題目理解
  • 2.2 動態規劃

這一遍刷dp的題目就很輕松了。

1 63 Unique Paths II

1.1 題目描述

A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).

Now consider if some obstacles are added to the grids. How many unique paths would there be?

An obstacle and space is marked as 1 and 0 respectively in the grid.

輸入:整數數組grid,表示一個mxn的方格,grid[i][j]=1表示是障礙,不能通過;grid[i][j]=0表示可以通過。
輸出:能夠從左上角走到右下角的不重復的路徑數
規則:只能向下或者向右走

Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
Output: 2
Explanation: There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:

  • Right -> Right -> Down -> Down
  • Down -> Down -> Right -> Right
  • 1.2 動態規劃解決

    class Solution {public int uniquePathsWithObstacles(int[][] obstacleGrid) {if(obstacleGrid[0][0]==1) return 0;int m = obstacleGrid.length;int n = obstacleGrid[0].length;int[][] dp = new int[m][n];dp[0][0] = (obstacleGrid[0][0]==1?0:1);for(int j=1;j<n;j++){dp[0][j]= (obstacleGrid[0][j]==1?0:dp[0][j-1]);}for(int i=1;i<m;i++){dp[i][0] = (obstacleGrid[i][0]==1?0:dp[i-1][0]);}for(int i=1;i<m;i++){for(int j=1;j<n;j++){dp[i][j] = (obstacleGrid[i][j]==0?dp[i-1][j]+dp[i][j-1]:0);}}return dp[m-1][n-1];} }

    2 64. Minimum Path Sum

    2.1 題目理解

    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.
    輸入:整數數組grid,表示一個mxn的方格,grid[i][j]表示通過方格的代價。
    輸出:能夠從左上角走到右下角的最小代價
    規則:只能向下或者向右走
    Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
    Output: 7
    Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.

    2.2 動態規劃

    class Solution {public int minPathSum(int[][] grid) {int m = grid.length;int n = grid[0].length;int[][] dp = new int[m][n];dp[0][0] = grid[0][0];for(int i=1;i<m;i++){dp[i][0] = dp[i-1][0]+grid[i][0];}for(int j=1;j<n;j++){dp[0][j] = dp[0][j-1]+grid[0][j];}for(int i=1;i<m;i++){for(int j=1;j<n;j++){dp[i][j] = Math.min(dp[i-1][j],dp[i][j-1])+grid[i][j];}}return dp[m-1][n-1];} }

    總結

    以上是生活随笔為你收集整理的63. Unique Paths II and 64. Minimum Path Sum的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。