LeetCode 64 最小路徑和
阿新 • • 發佈:2020-07-20
Leetcode 64 最小路徑和
典型的動態規劃問題
/**動態規劃 * 1. DP[i][j]表示從起點(0,0)到(i,j)位置的最小路徑 * 2. DP[i][j]只與DP[i-1][j]、DP[i][j-1]有關 * 3. DP[i][j] = Min(DP[i-1][j], DP[i][j-1]) + grid[i][j] */ /*第一種: 二維DP陣列*/ //用二維陣列儲存grid中每一個位置上的DP值 class Solution { public int minPathSum(int[][] grid) { if(grid==null || grid.length==0 || grid[0].length==0) return 0; int[][] dp = new int[grid.length][grid[0].length]; /*狀態遞推: 按行*/ for(int i=0; i<grid.length; i++){ for(int j=0; j<grid[0].length; j++){ if(i==0 && j==0) dp[i][j] = grid[i][j]; else if(i==0) dp[i][j] = dp[i][j-1] + grid[i][j]; else if(j==0) dp[i][j] = dp[i-1][j] + grid[i][j]; else dp[i][j] = Math.min(dp[i][j-1], dp[i-1][j]) + grid[i][j]; } } return dp[grid.length-1][grid[0].length-1]; } } /*第二種: 一維DP陣列*/ //用一維陣列每次儲存上一行的DP結果,則下一行DP結果直接在原陣列基礎上儲存 class Solution { public int minPathSum(int[][] grid) { if(grid==null || grid.length==0 || grid[0].length==0) return 0; int[] dp = new int[grid[0].length]; /*狀態遞推: 按行*/ for(int i=0; i<grid.length; i++){ for(int j=0; j<grid[0].length; j++){ if(i==0 && j==0) dp[j] = grid[i][j]; else if(i==0) dp[j] = dp[j-1] + grid[i][j]; else if(j==0) dp[j] = dp[j] + grid[i][j]; else dp[j] = Math.min(dp[j-1], dp[j]) + grid[i][j]; } } return dp[grid[0].length-1]; } } /*第三種: 無需額外空間*/ class Solution { public int minPathSum(int[][] grid) { if(grid==null || grid.length==0 || grid[0].length==0) return 0; /*狀態遞推: 按行*/ for(int i=0; i<grid.length; i++){ for(int j=0; j<grid[0].length; j++){ if(i==0 && j==0) continue; else if(i==0) grid[i][j] = grid[i][j-1] + grid[i][j]; else if(j==0) grid[i][j] = grid[i-1][j] + grid[i][j]; else grid[i][j] = Math.min(grid[i][j-1], grid[i-1][j]) + grid[i][j]; } } return grid[grid.length-1][grid[0].length-1]; } }