leetcode ---Unique Paths
2016-02-24 22:06
260 查看
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?(二维图像,只能往右或下走一步,从左上角到右下角一共多少种走法?)方法一:确定到任意一个点能有多少种走法?当x=0或y=0时,只能有一种;当x!=0 且 y!=0时,有 matrix[y][x]=matrix[y-1][x] + matrix[y][x-1]种走法;用 (上+左)代码:
public class Solution {
int[][] matrix;
public int uniquePaths(int m, int n) {
matrix = new int
[m];
for(int y=0; y<n; y++) {
for(int x=0; x<m; x++) {
//Fill top row and left most row with 1s
if(x == 0 || y==0) matrix[y][x]=1;
else {
matrix[y][x]=matrix[y-1][x] + matrix[y][x-1]; //相当于把每个点的走法种类都表示出来
}
}
}
return matrix[n-1][m-1]; //返回的时候要注意,不要越界
}
}方法二:知道从左上到右下,一共有m+n-2步,就分为两类,一类是右(m-1)步;一类是下(n-1)步; 题目转换为:在m+n-2步中,挑选哪些步是右(下)的
public class Solution {
}
public class Solution {
int[][] matrix;
public int uniquePaths(int m, int n) {
matrix = new int
[m];
for(int y=0; y<n; y++) {
for(int x=0; x<m; x++) {
//Fill top row and left most row with 1s
if(x == 0 || y==0) matrix[y][x]=1;
else {
matrix[y][x]=matrix[y-1][x] + matrix[y][x-1]; //相当于把每个点的走法种类都表示出来
}
}
}
return matrix[n-1][m-1]; //返回的时候要注意,不要越界
}
}方法二:知道从左上到右下,一共有m+n-2步,就分为两类,一类是右(m-1)步;一类是下(n-1)步; 题目转换为:在m+n-2步中,挑选哪些步是右(下)的
代码:
public class Solution {
public int uniquePaths(int m, int n) { long result = 1; for(int i=0;i<Math.min(m-1,n-1);i++) result = result*(m+n-2-i)/(i+1); //公式 return (int)result; }
}
相关文章推荐
- UEditor 报错:Uncaught ReferenceError: UE is not defined; Uncaught ReferenceError: UM is not defined
- ios-UI控件精讲之【6】-UIImageView
- ios-UI控件精讲之【5】-UIImage
- 通过Gradle来取的Jenkins的build
- UI美化概述
- suid seuid 当前用户ID 有效用户ID
- 5.UINavigationController
- web.xml is missing and <failOnMissingWebXml> is set to true
- iOS-UI-基本控件之UISwitch
- UICollectionView 使用 介绍
- String,StringBuffer,StringBuilder三者区别
- deque向量
- UITextField知多少
- 持续集成(CI)-build, test, and deploy & 自动化编译系统 mark & learn
- Android--UI控件的使用格式化
- iOS 开发之动画篇 - 从 UIView 动画说起
- 深入分析Parquet列式存储格式
- POJ - 3481 Double Queue
- hasshmap输出value
- ios隐藏UItableview下面多余的tableview的线条CELL / 隐藏脚视图