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]。意思就是到一个特定点的路径条数是到其左侧或者上侧点的路径条数的总和。

代码如下:

 class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int> > ans(m, vector<int>(n, ));
for(int i = ; i < m; ++i)
ans[i][] = ;
for(int j = ; j < n; ++j)
ans[][j] = ; for(int i = ; i < m; ++i){
for(int j = ; j < n; ++j){
ans[i][j] = ans[i - ][j] + ans[i][j - ];
}
}
return ans[m - ][n - ];
}
};

还有一种方法是使用dfs来实现,但是数大了就容易超时,这题的本意可能就是dfs,这里把代码放上:

 class Solution {
public:
int uniquePaths(int m, int n) {
times = ;
maxHor = m, maxVer = n;
dfs(,);
return times;
}
void dfs(int hor, int ver){
if((hor == maxHor - ) && (ver = maxVer - ))
times++;
else{
if(hor + < maxHor)  //注意这里不是while
dfs(hor + , ver);
if(ver + < maxVer)
dfs(hor, ver + );
}
}
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][n];
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];
}
}

最新文章

  1. 参数table_open_cache
  2. CSS的Hack技术
  3. 要当好JavaScript程序员:5个debug技巧
  4. 【position也可以很复杂】当弹出层遇上了鼠标定位(上)
  5. Virtualbox虚拟机安装CentOS6.5图文详细教程
  6. LICEcap GIF 屏幕录制工具
  7. listView异步处理图片下载缓存
  8. HDU 1199 - Color the Ball 离散化
  9. 作死上CODEVS,青铜题
  10. python--Selectors模块/队列
  11. java的8种基础类型
  12. form表单提交数据,页面必定会刷新,ajax提交数据不会刷新,做到悄悄提交,多选删除,ajax提交实例
  13. php-kafka
  14. Luogu P2880 [USACO07JAN]平衡的阵容Balanced Lineup (ST表模板)
  15. (第7篇)灵活易用易维护的hadoop数据仓库工具——Hive
  16. lua -- 所有UI组件的基类
  17. EntityFrameworkCore概览
  18. 小程序开发 绑定自定义数据data- 及JS获取
  19. input文字颜色、光标颜色
  20. 对一个前端使用AngularJS后端使用ASP.NET Web API项目的理解(1)

热门文章

  1. 004-搭建框架-实现AOP机制【一】代理技术
  2. 模拟美式橄榄球比赛数据(R)
  3. android学习二---解决ADT Buddle无法自动生成layout和res
  4. spring cloud 使用feign 遇到问题
  5. 使用C# .NET 将结构数组绑定到 Windows 窗体的方法
  6. windows安装pywin32
  7. 一句white-space:nowrap解决IE6,IE7下浮动元素不自动换行
  8. freemarker入门实例与源码研究准备工作
  9. 使用kibana进行简单的CRUD和版本控制
  10. 手动用maven安装jar的命令