[LeetCode] Unique Paths
来源:互联网 发布:手机淘宝怎么用信用卡 编辑:程序博客网 时间:2024/05/21 23:57
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?
最基础的动态规划,但是可以用组合数学的思想解决:
public class Solution {//假如是一个5*5的矩阵//1,1,1,1,1//1,2,3,4,5 //1,3,6,10,15//1,4,10,20,35//1,5,15,35,70//这样发现特别像杨辉三角(本人数学太差-也不懂其中的奥秘)//总之,我们还可以以另外一种方式计算,那就是数学方法://相当于从最左端到最右下角-我们需要向右走(n-1)步向下走(m-1)步//那么,我们只需要在(m+n-2)步中选出向右走的或者向下走的步数就可以了://因此很简单的数学公式了!//但是最简单的数学公式如果暴力求解不是很乐观,因此还是结合最开始的动态规划,这种动态规划实际上就是一种组合数//C(m+n-2,m-1) public int uniquePaths(int m, int n) { return CMN(m+n-2,n-1); } public int CMN(int m,int n){ n=Math.min(m-n, n);//zhe这句一定要有 目的是让long不越界 long re=1; for(int i=m,j=1;j<=n;i--,j++){ re*=i; re/=j; } return (int)re; } //这个代码是不可以的 无论令re为double型还是long型 (long型可能造成数组越界 double型会导致精确度不够 结果和理论结果差1)// public int CMN(int m,int n){// long re=1;// for(int i=m,j=1;j<=n;i--,j++){ // re*=i;// re/=j;// } // return (int)re;// }}
注意:如果用long型存储结果依然会越界 而用double会因为精度问题造成结果错误,所以这一步至关重要:
n=Math.min(m-n, n);
阅读全文
1 0
- leetcode Unique Paths && Unique Paths
- Leetcode-Unique Paths&Unique PathsII
- [LeetCode] Unique Paths and Unique Paths II
- leetcode--Unique Paths && Unique Paths ii
- leetcode--Unique Paths && Unique Paths ii
- 【Leetcode】【python】Unique Paths/Unique Paths II
- LeetCode: Unique Paths
- LeetCode: Unique Paths II
- [Leetcode] Unique Paths
- [Leetcode] Unique Paths II
- LeetCode : Unique Paths
- LeetCode : Unique Paths II
- leetcode 9: Unique Paths
- [LeetCode] Unique Paths
- [LeetCode] Unique Paths II
- [LeetCode]Unique Paths
- [LeetCode]Unique Paths II
- [LeetCode] Unique Paths
- RxJava 与 Retrofit 结合的最佳实践
- python011 -- 迭代器 生成器
- iOS 横向展示瀑布流 排列不规则长度标题的UIButton
- Yii2 User cookie 登录原理_TERRY
- 分别在Tomcat,spring初始化时注册监听器
- [LeetCode] Unique Paths
- MFC读取Excel例子(OLE/COM)
- Python之数组(array)使用方法总结与Numpy中的数组用法
- Docker学习笔记-Docker端口映射
- Linux(Ubuntu16.04)自学笔记,资源整理
- Mysql--key
- AngularJS model !
- 关于计算机视觉(随谈)
- Smart210启动流程、链接地址、复制代码等,解决串口控制台不好使问题