Unique Paths
2015-08-19 19:00
316 查看
原题如下(链接:https://leetcode.com/problems/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?
解题思路:可以类比到青蛙跳台阶的题,其实只要找到一个递推公式就可以了,F(m,n) = F(m-1, n) + F(m, n-1);
递归求解的话会超时,但是比较容易理解,代码如下:
把递归改成循环可以顺利AC,C++代码如下:
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?
解题思路:可以类比到青蛙跳台阶的题,其实只要找到一个递推公式就可以了,F(m,n) = F(m-1, n) + F(m, n-1);
递归求解的话会超时,但是比较容易理解,代码如下:
[code] int uniquePaths(int m, int n) { if(m < 1 || n < 1) return 0; if(n == 1 || m == 1) return 1; else return uniquePaths(m-1, n) + uniquePaths(m, n-1); }
把递归改成循环可以顺利AC,C++代码如下:
[code] int uniquePaths(int m, int n) { if(m < 1 || n < 1) return 0; int **mn = new int*[m]; for(int i=0; i<m; i++){ mn[i] = new int ; } for(int i=0; i<m; i++){ mn[i][0] = 1; } for(int i=0; i<n; i++){ mn[0][i] = 1; } for(int i=1; i<m; i++){ for(int j=1; j<n; j++){ mn[i][j] = mn[i][j-1] + mn[i-1][j]; } } return mn[m-1][n-1]; }
相关文章推荐
- A Beginner’s Guide to Eigenvectors, PCA, Covariance and Entropy
- poj3625 Building Roads(最小生成树)
- Android第三讲——五大布局(UI)
- 设计模式之建造者模式(Builder Pattern)
- Version和Build字段的关系
- Android 中MenuInflater的使用(布局定义菜单
- [LeetCode]Unique Paths II
- [LeetCode]Unique Paths
- StringBuffer和StringBuilder的区别
- UIViewController的详细介绍
- iOS UIScrollView实现无限滚动,思路与代码
- iOS:UITextField中文输入法输入时对字符长度的限制
- 将webkit内核封装为duilib的浏览器控件
- 分享个Duilib中基于wke的浏览器控件
- HDU 2767--Proving Equivalences【scc缩点构图 && 求向图中最少增加多少条边才可以使新图强连通】
- sql server UI怎么设置自增加id?
- iOS SDK详解之UIToolBar
- 树莓派2在U8300W平台上用pppd拨号时出现“pppd: The remote system is required to authenticate itself”
- mysql 错误 SQL Error: 1366: Incorrect string value: "\xE8\xAF\xA6\xE7\xBB\x86…" for column "address"
- class priority_queue<> 简单介绍