Unique Paths--lintcode
来源:互联网 发布:ftp的默认端口 编辑:程序博客网 时间:2024/06/18 06:22
Description
A robot is located at the top-left corner of a m x n grid.
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.
How many possible unique paths are there?
Notice
m and n will be at most 100.
Example
Given m = 3 and n = 3, return 6.
Given m = 4 and n = 5, return 35.
这个题目考的是动态规划。根据题目,首先想到的是二维数组。从[0][0]到[m-1][n-1]。假设 m=3 n=3,。
分析:从00到m-1n-1有多种路径。首先在原点时,有往右或往下 两种走法。不管走哪一边,也有两种走法。所以转化思路,给每个位置赋上从00到该坐标的路径个数。首先全部默认值为1.然后再逐个赋值。如图:
可以看到在11位置有两种路径 是从它的左边10或上边01进,而00到01或到10只有一种路径,所以11位置的路径是 2=1+1。在21位置也是从上面或左边进入。20的值是1,11的值是2,所以21值为3=2+1.同理可以得到22的路径个数是6=3+3.
public int uniquePaths(int m, int n) { int[][] a = new int[m][n]; for(int i=0;i<m;i++){ a[i][0]=1; } for(int j=0;j<n;j++){ a[0][j]=1; } for(int i=1;i<m;i++){ for(int j=1;j<n;j++){ a[i][j]=a[i-1][j]+a[i][j-1]; } } return a[m-1][n-1];* }
上面的代码是看成二维数组。
下面讲解看成一维数组。
思路和上面的一样。同样给这个一维数组赋值全为1。在二维数组里当i=0的时候 00 到哪一列都只有一条路径。当i=1时,10值为1 ,01值为1,所以11值为2=1+1.在一维数组里开始时 值全是1,之后该坐标的值是其左边的值加上自己本身的值。因为该坐标的上面坐标变成了该坐标
如图 开始全为1,如第一行。到第二轮的时候坐标[1]的值是其本身的值1+坐标[0]的值1=2.
public int uniquePaths(int m, int n) { int[] a=new int[n]; for(int j=0;j<n;j++){ a[j]=1; } for(int i=1;i<m;i++){ for(int j=1;j<n;j++){ a[j]+=a[j-1]; } } return a[n-1]; }
参考网址:http://blog.csdn.net/ljiabin/article/details/41805859
- lintcode: Unique Paths
- lintcode: Unique Paths II
- Unique Paths--lintcode
- [Lintcode] Unique Paths I,II
- lintcode unique-paths 不同的路径
- lintcode unique-paths-ii 不同的路径ii
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- selenium 基本方法使用二_javascript的应用_对滚动条的操作
- js跨域详解
- 红黑树深入剖析及Java实现(图文并茂娓娓道来)
- git管理项目思想
- 多无线通信终端并行自动化射频测试系统开发与应用
- Unique Paths--lintcode
- Hibernate入门(2):基本使用
- 【15】vue.js — 动画
- Python学习第一课
- tensorflow:如何将tensor A 的形状reshape为tensor b 的形状
- 在 Linux 上配置 mongodb
- Consul实现原理系列文章3: Consul的整体架构
- Python【函数:调用函数 定义函数 函数的参数 递归函数】学习注意事项
- PAT--1079. Total Sales of Supply Chain