leetCode-Unique Paths
来源:互联网 发布:网络追逃人员查询系统 编辑:程序博客网 时间:2024/06/11 00:23
Description:
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?
Note: m and n will be at most 100.
Solution:
#设c[x][y]为从00到(x,y)可能的路径,c[x][y] = c[x][y - 1] +c[x - 1][y],而第0行和第0列由于只能往右或者往下,所以都设置为1 public class Solution { public int uniquePaths(int m, int n) { int[][] map = new int[m][n]; for(int i = 0; i<m;i++){ map[i][0] = 1; } for(int j= 0;j<n;j++){ map[0][j]=1; } for(int i = 1;i<m;i++){ for(int j = 1;j<n;j++){ map[i][j] = map[i-1][j]+map[i][j-1]; } } return map[m-1][n-1]; }}
Best Solution:
//相当于把上面例子的二维数组缩短成一维数组了class Solution { public int uniquePaths(int m, int n) { int[] row = new int[n]; Arrays.fill(row,1); for ( int i = 1; i < m; i++){ for ( int j = 1; j < n; j++){ row[j]+=row[j-1]; } } return row[n-1]; }}
总结:
这一题是典型的动态规划。我们首先可以想到递归,而递归一个问题就是有重复计算,我们可以想到用一个数组保存计算过的c[x][y],等到下次遇上的时候直接取值即可,效率会大大提高,但是还是不够好,因为递归有栈帧的问题,于是我们想到将递归转化为递推,既然每个c[x][y]=c[x - 1][y] + c[x][y - 1],那么我们可以把第一行,第一列的c[x][y]先求出来,然后遍历接下来的矩阵,用这个转化公式求值即可。
可以看一下这篇文章,动态规划讲的比较详细:
http://blog.csdn.net/baidu_28312631/article/details/47418773
阅读全文
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
- Python3多进程学习
- sublime text安装及使用
- Java程序员的日常 —— Java类加载中的顺序
- Training set、Validation set and Testing set
- 血淋林的例子告诉你,为什么防“上传漏洞”要用白名单
- leetCode-Unique Paths
- ThinkPHP5.1 闭包路由 直接输出数据 不需要定义控制器
- eclipse和tomcat7相关配置问题
- ORACLE ROWNUM分页总结
- 1> python hello word
- JAVA程序员三年从入门到精通的视频资料
- Eclipse解决中文字体设置
- NOT EXISTS
- Find Pivot Index[Leetcode 724]