LeetCode OJ:Unique Paths(唯一路径)
2015-10-22 15:47
483 查看
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*n网格,求从左上角到右下角的路径条数即可,用dp很容易解决,推到式为res[i][j] = res[i - 1][j] + res[i][j - 1]。意思就是到一个特定点的路径条数是到其左侧或者上侧点的路径条数的总和。
代码如下:
还有一种方法是使用dfs来实现,但是数大了就容易超时,这题的本意可能就是dfs,这里把代码放上:
java版本如下所示,dp实现:
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*n网格,求从左上角到右下角的路径条数即可,用dp很容易解决,推到式为res[i][j] = res[i - 1][j] + res[i][j - 1]。意思就是到一个特定点的路径条数是到其左侧或者上侧点的路径条数的总和。
代码如下:
class Solution { public: int uniquePaths(int m, int n) { vector<vector<int> > ans(m, vector<int>(n, 0)); for(int i = 0; i < m; ++i) ans[i][0] = 1; for(int j = 0; j < n; ++j) ans[0][j] = 1; for(int i = 1; i < m; ++i){ for(int j = 1; j < n; ++j){ ans[i][j] = ans[i - 1][j] + ans[i][j - 1]; } } return ans[m - 1][n - 1]; } };
还有一种方法是使用dfs来实现,但是数大了就容易超时,这题的本意可能就是dfs,这里把代码放上:
class Solution { public: int uniquePaths(int m, int n) { times = 0; maxHor = m, maxVer = n; dfs(0,0); return times; } void dfs(int hor, int ver){ if((hor == maxHor - 1) && (ver = maxVer - 1)) times++; else{ if(hor + 1 < maxHor) //注意这里不是while dfs(hor + 1, ver); if(ver + 1 < maxVer) dfs(hor, ver + 1); } } private: int times; int maxHor; int maxVer; };
java版本如下所示,dp实现:
public class Solution { public int uniquePaths(int m, int n) { if(m == 0 || n == 0) return 0; int [][] grid = new int [m] ; for(int i = 0; i < m; ++i){ grid[i][0] = 1; } for(int i = 0; i < n; ++i){ grid[0][i] = 1; } for(int i = 1; i < m; ++i){ for(int j = 1; j < n; ++j){ grid[i][j] = grid[i-1][j] + grid[i][j-1]; } } return grid[m-1][n-1]; } }
相关文章推荐
- Requested a new session but one was in progress
- Metal Tips and Techniques
- IOS UITextView 光标的位置,大小,宽度,高度设置问题
- easyui之combotree
- array_values() 函数
- Mapped Statements collection does not contain value for原因列举
- 键盘弹出,视图向上移,键盘高度遮住UITextField的解决方法
- AutoLayout深入浅出五[UITableView动态高度]
- Android 高级UI设计笔记03:使用Scroller实现绚丽的ListView左右滑动删除Item效果(转载)
- UITableView+FDTemplateLayoutCell源码学习笔记
- db file sequential reads
- MySql系列:中文写入数据库出现错误java.sql.SQLException: Incorrect string value: '\xE5\xxxx' for column 'xxxx' at row 1及其解决方法
- ServletRequest中getReader()和getInputStream()只能调用一次的解决办法
- iOS8 自定义UITabBar (使用popToViewController导致的UITabBarButton重叠的问题)
- 卓越管理的实践技巧(4)如何才能给予有效的反馈 Guide to Giving Effective Feedback
- HDU 4126 Genghis Khan the Conqueror(最小生成树+树形DP)
- Android应用程序未安装错误:Installation error: INSTALL_FAILED_UID_CHANGED
- 解决 Error:No suitable device found: no device found for connection "System eth0"
- android stuido 自定义 代码块
- 【PAT】 1085. Perfect Sequence (25)