LeetCode第[62]题(Java):Unique Paths 及扩展
题目:唯一路径(机器人走方格)
难度: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?
翻译:
机器人位于m x n网格的左上角(在下图中标记为“开始”)。
机器人只能在任何时间点移动或向右移动。机器人正试图到达网格的右下角(在下图中标记为“Finish”)。
有多少种可能的路径?

Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2
Output: 3
Example 2:
Input: m = 7, n = 3
Output: 28
我的思路:动态规划题,每个点(m,n)都是由(m-1,n)+(m,n-1)这两个点的可能数之和。最简单的方法就是用递归来实现。
我的代码:
     public int uniquePaths(int m, int n) {
         if (m == 1 || n==1) {
             return 1;
         }
         return uniquePaths(m,n-1) + uniquePaths(m-1,n);
     }
我的复杂度:O(m*n) 空间复杂度也是O(m*n) ——递归深度
结果:41 / 62 test cases passed. Time Limit Exceeded
Last executed input: 51 9
递归就是这样,代码很简单,但是运行速度很慢,稍微大一点就会超时。
答案代码:
     public int uniquePaths(int x, int y) {
         int dp[][] = new int[x][y];
         for(int i = 0; i< x;i++){
             for(int j = 0;j<y;j++){
                 if (i == 0 || j == 0) {
                     dp[i][j] = 1;
                     continue;
                 }
                 dp[i][j] = dp[i-1][j] + dp[i][j-1];
             }
         }
         return dp[x-1][y-1];
     }
答案复杂度:O(m*n) 空间复杂度也是O(m*n) 虽然复杂度都一样,但是由于用迭代替换了递归,运行速度大大提高。
答案思路:递归无非就是把本层的计算调用深一层的计算,然后将深一层的结果返回,所以如果将从第一层到最后一层所有的值都计算出来并由某种数据结构保存,那么就可以直接迭代进行计算。
所以一维的递归:一维只会与一维相关,所以一路直线迭代即可。例如:求阶乘(只与上一个有关,记录一个即可)、斐波那契数列(与上两个有关,需要记录两个)
二维的递归:每一个元素都与两个维度相关,所以得借用二维数组来记录所有值。
扩展:当x == y的时候,此时为正方格,是否有更好的方法?
因为此时类似于卡特兰数,此时有 f(n+1)=f(n)* (4*n-2),所以代码中加入方形判断可以优化方形的计算速度,如下:
        if (x == y) {
            int ans = 1;
            for (int i = 1; i < x; i++) {
                ans = ans * (4*i-2)/i;
            }
            return ans;
        } 
注意:当要使用 “ *= ” 这种符号的时候,如果右边是一个表达式且含有 除号 ,那么最好还是不要使用,因为这个运算符是先运算右边再乘自己,所以有可能右边的计算顺序就不对了。
例如当x==y==4的时候 此时ans = =6 而 i ==3 ,如果使用 ans *= (4*i -2)/i; 所以先计算右边就有 10 / 3 = 3, 然后再乘以6 最后结果为18,结果错误。
而使用 ans = ans * (4*i-2)/i; 就不会有此错误。
LeetCode第[62]题(Java):Unique Paths 及扩展的更多相关文章
- 【LeetCode每天一题】Unique Paths(唯一的路径数)
		
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).The ...
 - LeetCode第[18]题(Java):4Sum 标签:Array
		
题目难度:Medium 题目: Given an array S of n integers, are there elements a, b, c, and d in S such that a + ...
 - LeetCode第[1]题(Java):Two Sum   标签:Array
		
题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...
 - LeetCode第[46]题(Java):Permutations(求所有全排列)  含扩展——第[47]题Permutations 2
		
题目:求所有全排列 难度:Medium 题目内容: Given a collection of distinct integers, return all possible permutations. ...
 - LeetCode第[1]题(Java):Two Sum   (俩数和为目标数的下标)——EASY
		
题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...
 - 动态规划小结 - 二维动态规划 - 时间复杂度 O(n*n)的棋盘型,题 [LeetCode] Minimum Path Sum,Unique Paths II,Edit Distance
		
引言 二维动态规划中最常见的是棋盘型二维动态规划. 即 func(i, j) 往往只和 func(i-1, j-1), func(i-1, j) 以及 func(i, j-1) 有关 这种情况下,时间 ...
 - [LeetCode][Java] Unique Paths II
		
题目: Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. H ...
 - 【Leetcode】【Medium】Unique Paths
		
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The ...
 - 【Leetcode】【Medium】Unique Paths II
		
Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. How m ...
 
随机推荐
- iOS中nil 、NULL、 Nil 、NSNull
			
nil,定义一个空的实例,指向OC中对象的空指针. 示例代码: NSString *someString = nil; NSURL *someURL = nil; id someObject = ni ...
 - js实现模糊查询
			
1.简述 实现模糊查询方法有很多种,后端可以实现,前端使用js也可以实现. 后端实现起来需要根据输入框中搜索的关键字,去后台拼接SQL语句查询. 前端直接使用字符串的indexOf()方法或者正则表达 ...
 - SVN学习一
			
svn是subversion的缩写形式. svn是一个版本控制软件. 目标: 1.允许开发同时进行工作. 2.不覆盖其他人的文件变化. 3.保持历史的每一个版本. 版本控制系统分为两类: 1.集中式版 ...
 - delphi webbrowser post自动登录
			
delphi webbrowser post自动登录 var EncodedDataString: WideString; PostData: OleVariant; Headers: ...
 - appcmd应用
			
appcmd资料: http://www.jb51.net/article/36024.htm 官方文档:https://docs.microsoft.com/zh-cn/iis/get-starte ...
 - tomcat 启动报错(tomcat org.apache.catalina.core.StandardContext startInternal)
			
转载:https://blog.csdn.net/chenlong316048157/article/details/18698611 org.apache.catalina.core.Standar ...
 - PAT 天梯赛 L1-001 【水】
			
L1-001. Hello World 时间限制 400 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 这道超级简单的题目没有任何输入. 你只需要在一行中输 ...
 - 2018 Multi-University Training Contest 1 - D  Distinct Values (STL+双指针)
			
题意:数量为N的序列,给定M个区间,要求对每个区间Li,Ri,都有al..r (l≤i<j≤r), ai≠aj.构造这个序列使其字典序最小. 分析:如果对于每个所给区间都暴力扫一遍,1e5的数据 ...
 - html使用笔记
			
1. HTML 表单内容设置最大长度:<input type="text" name="fullname" maxlength="85&quo ...
 - hadoop19---动态代理
			
Action调用service里面的方法,动态代理:改变方法的实现在方法前后加逻辑不是加新方法. 在学习Spring的时候,我们知道Spring主要有两大思想,一个是IoC,另一个就是AOP,对于Io ...