• LeetCode之动态规划


    62. Unique Paths

      

    Total Accepted: 86710 Total Submissions: 239084 Difficulty: Medium

    A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

    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).

    How many possible unique paths are there?

    使用动态规划来求解本题,在每个节点处,只有两个选择,向下或者向右走。本节点可由上一个节点向下或者向右走过来,两种方法:

    1)使用一个二位数组count[i][j]来表示从起始点到达坐标(i,j)的,有两种,(i-1,j)-->(i,j)及(i,j-1)-->(i,j),即count[i][j] = count[i-1][j]+count[i][j-1],此时时间复杂度为O(mn),空间复杂度为O(mn)

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

    2)使用一个数组count[i]来表示从起始点到达某一行某一列的路径数量,此时有,count[i] = count[i-1]+count[i],此时,时间复杂度为O(mn),空间复杂度为O(n):

    //因为只需求得最终结果,而不需要知道到达每一个坐标的路径数量
    public
    class Solution { public int uniquePaths(int m, int n) { int[] count = new int[n]; count[0]=1; for(int i=0;i<m;i++){ for(int j=1;j<n;j++){ count[i] = count[i-1]+count[i]; } } return count[n-1]; } }

    63. Unique Paths II

     

    Total Accepted: 65258 Total Submissions: 222092 Difficulty: Medium

    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.

  • 相关阅读:
    成功解决vc6.0智能提示消失的BUG
    如何在vc6,vc7,vc8下编译x264
    Visual C++ 操作MS Offfice 控件
    在英文版Visual Studion 2005 professional 中使用 Windows Mobile 2003 SE中文模拟器
    x264 20060731 svn 版的编码移植
    泛型算法:Tips
    05年度EmilMatthew’s Blog文档整理
    常用软件滤波方法及其示例程序
    windows server 2003 配置
    TI C64X 视频处理应用编程重点内容提示
  • 原文地址:https://www.cnblogs.com/coffy/p/5456458.html
Copyright © 2020-2023  润新知