ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

LeetCode刷题之——62. Unique Paths(单一路径)

2020-07-09 15:37:25  阅读:266  来源: 互联网

标签:Paths right int 路径 robot 62 grid corner 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?

 

 

 

Constraints:

  • 1 <= m, n <= 100
  • It's guaranteed that the answer will be less than or equal to 2 * 10 ^ 9.

 


以上是问题描述。

我的算法如下:

假设一个3*7的网格:

 

大概的思想是这样的:看一下对于除去左上角0,0的剩余所有点中的任意一点来说,从左上角0,0走到这一点有几条路。(简称路径数)

比如,最左侧和最上面的所有点都只有一条路径(直线),因为机器人只能往下或者往右走。

由此,可以算出剩下任意一点的路径数:路径数 = 左侧点的路劲数 + 上侧点的路径数。

那么到右下角的点的路径数也就非常容易知道了。

代码如下:

 1 class Solution {
 2 public:
 3     int uniquePaths(int m, int n) {
 4         int** mat =new int *[m];
 5         for(int i=0;i<m;i++){
 6             mat[i] = new int[n];
 7         }
 8             
 9         
10         for(int i=0;i<m;i++){
11             for(int j=0;j<n;j++){
12                     mat[i][j]=1;
13             }
14         }
15         
16         for(int i=1;i<m;i++){
17             for(int j=1;j<n;j++){
18                 mat[i][j]=mat[i-1][j]+mat[i][j-1];
19             }
20         }
21         
22         int res= mat[m-1][n-1];
23             
24         for(int i=0;i<m;i++)
25         delete []mat[i];
26     delete []mat;
27         
28         return res;
29         
30     }
31 };

注:难度为medium

 

标签:Paths,right,int,路径,robot,62,grid,corner,LeetCode
来源: https://www.cnblogs.com/mrlonely2018/p/13273971.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有