/** * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). * <p> * 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). * <p> * How many possible unique paths are there? * <p> * Input: m = 3, n = 2 * Output: 3 * Explanation: * From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: * 1. Right -> Down -> Down * 2. Down -> Down -> Right * 3. Down -> Right -> Down */ privatestaticclassSolution{ publicintuniquePaths(int m, int n){ int[][] matrix = newint[m][n]; for (int i = 0; i < n; i++) { matrix[m - 1][i] = 1; } for (int i = 0; i < m; i++) { matrix[i][n - 1] = 1; } for (int i = m - 2; i >= 0; i--) { for (int j = n - 2; j >= 0; j--) { matrix[i][j] = matrix[i + 1][j] + matrix[i][j + 1]; } } return matrix[0][0]; } } }
/** * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). * <p> * 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). * <p> * Now consider if some obstacles are added to the grids. How many unique paths would there be? * <p> * An obstacle and space is marked as 1 and 0 respectively in the grid. */ privatestaticclassSolution{ publicintuniquePathsWithObstacles(int[][] obstacleGrid){ int m = obstacleGrid.length; int n = obstacleGrid[0].length; if (m == 1 && n == 1) { if (obstacleGrid[0][0] == 0) return1; elsereturn0; } if (obstacleGrid[m - 1][n - 1] == 1) return0; for (int i = n - 2; i >= 0; i--) { if (obstacleGrid[m - 1][i] == 1) obstacleGrid[m - 1][i] = 0; else { if (i == n - 2) obstacleGrid[m - 1][i] = 1; else obstacleGrid[m - 1][i] = obstacleGrid[m - 1][i + 1]; } } for (int i = m - 2; i >= 0; i--) { if (obstacleGrid[i][n - 1] == 1) obstacleGrid[i][n - 1] = 0; else { if (i == m - 2) obstacleGrid[i][n - 1] = 1; else obstacleGrid[i][n - 1] = obstacleGrid[i + 1][n - 1]; } } for (int i = m - 2; i >= 0; i--) { for (int j = n - 2; j >= 0; j--) { if (obstacleGrid[i][j] == 1) obstacleGrid[i][j] = 0; else { obstacleGrid[i][j] = obstacleGrid[i + 1][j] + obstacleGrid[i][j + 1]; } } } return obstacleGrid[0][0]; } } }
Minimum Path Sum
思路和上面两题一样 动规
1 2 3 4 5 6 7 8 9 10 11 12 13 14
private static class Solution { public int minPathSum(int[][] grid) { int m = grid.length; int n = grid[0].length; for (int i = m - 2; i >= 0; i--) grid[i][n - 1] += grid[i + 1][n - 1]; for (int i = n - 2; i >= 0; i--) grid[m - 1][i] += grid[m - 1][i + 1]; for (int i = m - 2; i >= 0; i--) { for (int j = n - 2; j >= 0; j--) { grid[i][j] += Math.min(grid[i + 1][j], grid[i][j + 1]); } } return grid[0][0]; } }