动态规划

Leetcode Diary

2016-12-08  本文已影响3人  VincentJianshu

DP Section

64_Minimum_Path_Sum

Simple DP

public class Solution {
    public int minPathSum(int[][] grid) {
        int row = grid.length;
        int col = grid[0].length;
        for (int i = 0; i < row - 1; i++) {
            grid[i+1][0] += grid[i][0];
        }
        for (int i = 0; i < col - 1; i++) {
            grid[0][i+1] += grid[0][i];
        }
        for (int i = 1; i < row; i++) {
            for (int j = 1; j < col; j++) {
                grid[i][j] += grid[i][j-1] > grid[i-1][j] ? grid[i-1][j] : grid[i][j-1];
            }
        }
        return grid[row-1][col-1];
    }
}

62_Unique_Paths

Simpler DP...

public class Solution {
    public int uniquePaths(int m, int n) {
        if (m == 0 || n == 0) return 0;
        int grid[][] = new int[m][n];
        for (int i = 0; i < m; i++) {
            grid[i][0] = 1;
        }
        for (int i = 1; i < n; i++) {
            grid[0][i] = 1;
        }
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                grid[i][j] = grid[i][j-1] + grid[i-1][j];
            }
        }
        return grid[m-1][n-1];
    }
}

174_Dungeon_Game

Elegant DP solution: create a healthGrid to store the least health needed, dp from finish point to start point, with Transition Format Dp[i][j] = max(1,min(dp[i+1][j],dp[i][j+1]) - grid[i][j]). It's also possible to dp on the original dungeon array, but I am too lazy to spare the effort. :(

public class Solution {
    public int calculateMinimumHP(int[][] dungeon) {
        int row = dungeon.length;
        int col = dungeon[0].length;
        int healthGrid[][] = new int [row][col];
        healthGrid[row - 1][col - 1] = Math.max(1, 1 - dungeon[row - 1][col - 1]);
        for (int i = row - 2; i >= 0; i--) {
            healthGrid[i][col - 1] = Math.max(1, healthGrid[i + 1][col - 1] - dungeon[i][col - 1]);
        }
        for (int i = col - 2; i >= 0; i--) {
            healthGrid[row - 1][i] = Math.max(1, healthGrid[row - 1][i + 1] - dungeon[row - 1][i]);
        }
        for (int i = row - 2; i >= 0; i--) {
            for (int j = col - 2; j >= 0; j--) {
                healthGrid[i][j] = Math.max(1, Math.min(healthGrid[i + 1][j], healthGrid[i][j + 1]) - dungeon[i][j]);
            }
        }
        return healthGrid[0][0];
    }
}
上一篇下一篇

猜你喜欢

热点阅读