[LeetCode] Unique Paths
来源:互联网 发布:淘宝退货率在哪里看 编辑:程序博客网 时间:2024/06/11 09:14
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.
解题思路:
数学题。共有路径数C(m-1 + n - 1, n-1)。计算的时候会用到阶层运算,因此要用longlong类型防止溢出,而且需要尽量先做除法运算。
class Solution {public: int uniquePaths(int m, int n) { long long result = 1; if(m<=1 || n<=1){ return result; } int j=n-1; for(int i=m+n-2; i>=m; i--){ while(j>1 && result%j==0){ result = result/j; j--; } result = result * i; } while(j>1 && result%j==0){ result = result/j; j--; } return (int)result; }};
update in 2015-07-28
方法2:回溯法。
d[i][j]表示从0,0到i,j的走法数,则有
d[i][j]=d[i-1][j]+d[i][j-1]
代码如下:
class Solution {public: int uniquePaths(int m, int n) { if(m<=0||n<=0){ return 0; } vector<vector<int>> d(m, vector<int>(n, 0)); d[0][0] = 1; for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ if(i>0){ d[i][j] += d[i-1][j]; } if(j>0){ d[i][j] += d[i][j-1]; } } } return d[m-1][n-1]; }};
0 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
- 【Matlab学习笔记】【函数学习】max()和max(max())的区别
- 自定义Notification添加点击事件
- Gym 100703K Word order 简单贪心
- spring利用ApplicationListener自启动
- CHttpFile POST 时 Cookie 疑问
- [LeetCode] Unique Paths
- Axure 倒计时使用变量
- Android性能优化技巧
- iOS tableView的刷新 笔记
- Android 性能优化之使用MAT分析内存泄露问题
- 2002 计算球体积
- IOS--UI 电影列表纯代码
- iOS Objective-C @property属性的用法
- poj 3009 Curling 2.0