zoukankan      html  css  js  c++  java
  • LeetCode 62. Unique Paths(所有不同的路径)

    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?

    Above is a 3 x 7 grid. How many possible unique paths are there?

    Note: m and n will be at most 100.


    题目标签:Array

      这道题目给了我们一个matrix 的m 和n, 让我们从[0,0] 开始,找到所有不同的路径到[m-1][n-1]。我们可以来看一个比原题简单一点的例子:

      3 * 3 matrix,我们设起点为1。每一个点代表的是,走到这个点的不同路径的数量

           1  0  0

           0  0  0

           0  0  0

      我们可以发现,机器人只能往右和下走,所以路径的可能只能来自于左和上。

      所以我们可以遍历matrix,把这个点的左边点,和上面点加起来,就等于到这个点的路径之和。

      1  1  1

      1  2  3

      1  3  6

      最后一个点,[m-1][n-1]就是所有不同路径的总数。

     

    Java Solution:

    Runtime beats 5.14% 

    完成日期:07/20/2017

    关键词:Array

    关键点:Dynamic Programming, 逆向思考

     1 public class Solution 
     2 {
     3     public int uniquePaths(int m, int n) 
     4     {
     5         int[][] matrix = new int[m][n];
     6         
     7         matrix[0][0] = 1; // start point
     8         
     9         for(int i=0; i<m; i++) // row
    10         {
    11             for(int j=0; j<n; j++) // column
    12             {
    13                 // get left
    14                 if(j-1 >=0)
    15                     matrix[i][j] += matrix[i][j-1];
    16                 // get top
    17                 if(i-1 >=0)
    18                     matrix[i][j] += matrix[i-1][j];
    19             }
    20         }
    21         
    22         return matrix[m-1][n-1];
    23     }
    24 }

    参考资料:

    http://www.cnblogs.com/grandyang/p/4353555.html

    LeetCode 算法题目列表 - LeetCode Algorithms Questions List

  • 相关阅读:
    JS LeetCode 1423. 可获得的最大点数简单题解
    SpringBoot 学集 (第六章) Docker
    Linux 学记 (第三章)
    Linux 学记 (第二章)
    Linux 学记 (第一章)
    SpringBoot 学集 (第五章) Web开发续
    SpringBoot 学集 (第四章)Web开发
    SpringBoot 学集 (第三章) 日志框架
    SpringBoot 学集 (第二章) 配置文件
    SpringBoot 学集 (第一章)
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7215733.html
Copyright © 2011-2022 走看看