• LeetCode 63. Unique Paths II


    题目如下:

    Follow up for "Unique Paths":
    
    Now consider if some obstacles are added to the grids. How many unique paths would there be?
    
    An obstacle and empty space is marked as 1 and 0 respectively in the grid.
    
    For example,
    There is one obstacle in the middle of a 3x3 grid as illustrated below.
    
    [
      [0,0,0],
      [0,1,0],
      [0,0,0]
    ]
    The total number of unique paths is 2.
    
    Note: m and n will be at most 100.

    思路:

    同 LeetCode 62. Unique Paths, 只不过决定每个res[i][j]的时候,都要先判断:obstacleGrid[i][j]如果等于1,则res[i][j]=0; 否则正常进行。

    本题代码:

    import java.util.Scanner;
    
    /**
     * Created by yuanxu on 17/4/13.
     */
    public class DP63 {
    
        public static int uniquePathsWithObstacles(int[][] obstacleGrid) {
            int m = obstacleGrid.length;
            int n = obstacleGrid[0].length;
            int res[][] = new int[m][n];// 数据从0开始
    
            // boundary condition
            res[0][0] = obstacleGrid[0][0] == 1 ? 0 : 1;
            for (int i=1; i<m; i++) {
                if (res[i-1][0] == 0) {
                    res[i][0] = 0;
                } else if (obstacleGrid[i][0] == 1) {
                    res[i][0] = 0;
                } else {
                    res[i][0] = 1;
                }
            }
            for (int j=1; j<n; j++) {
                if (res[0][j-1] == 0) {
                    res[0][j-1] = 0;
                } else if (obstacleGrid[0][j] == 1) {
                    res[0][j] = 0;
                } else {
                    res[0][j] = 1;
                }
            }
    
            // DP
            for (int i=1; i<m; i++) {
                for (int j=1; j<n; j++) {
                    if (obstacleGrid[i][j] == 1) {
                        res[i][j] = 0;
                    } else {
                        res[i][j] = res[i-1][j] + res[i][j-1];
                    }
                }
            }
    
            return  res[m-1][n-1];
        }
    
    
        public  static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
    //        int obstacleGrid[][] = {{0,0,0},{0,1,0},{0,0,0}};
    //        int obstacleGrid[][] = {{1}};
            int obstacleGrid[][] = {{0,0},{0,1}};
            System.out.println(uniquePathsWithObstacles(obstacleGrid));
        }
    }
  • 相关阅读:
    表格排序插件datatables
    dropzone手动上传
    上传文件插件dropzone的实例
    table加载慢
    利用touchslide实现tab滑动切换
    Qt之事件处理机制
    Qt容器组件(二)之QWidgetStack、QMdiArea、QDockWidget
    ActiveMQ之ActiveMQ-CPP安装及测试
    Qt容器组件(一)之QGroupBox、QScrollArea、QToolBox、QTabWidget
    Qt属性系统(Qt Property System)
  • 原文地址:https://www.cnblogs.com/pinganzi/p/6703033.html
Copyright © 2020-2023  润新知