1. 程式人生 > >leetcode64:Minimum Path Sum

leetcode64:Minimum Path Sum

思路:跟之前走方格的題差不多,只是狀態轉移方程稍微改變一下。dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];。

程式碼:

public class MinimumPathSum64 {

	public static void main(String[] args) {

//		int[][] num = { { 1, 3, 1 }, { 1, 5, 1 }, { 4, 2, 1 }};
		int[][] num = { { 1, 2,5 }, { 3,2,1 }};
		System.out.println(minPathSum(num));
	}

	public static int minPathSum(int[][] grid) {

		int[][] dp = new int[grid.length][grid[0].length];
		int sum = 0;
		for (int i = 0; i < grid[0].length; i++) {
			sum += grid[0][i];
			dp[0][i] = sum;
		}
		sum = 0;
		for (int i = 0; i < grid.length; i++) {
			sum += grid[i][0];
			dp[i][0] = sum;
		}

		for (int i = 1; i < dp.length; i++) {
			for (int j = 1; j < dp[0].length; j++) {
				dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
			}
		}
		return dp[dp.length - 1][dp[0].length - 1];
	}
}

輸出: