Unique Paths
来源:互联网 发布:javascript读取excel文件 编辑:程序博客网 时间:2024/06/05 22:38
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.
数学方法:卡特兰数。
public class Solution { public int uniquePaths(int m, int n) { if(m==1 || n==1) return 1; int N=m+n-2; double res=1.0; //cal N!/(n-1)!*(m-1)! for(int i=1;i<=m-1;i++){ res=res*(n+i-1)/i; } return (int)res; }}
dp解法。
public class Solution { public int uniquePaths(int m, int n) { int [][]f=new int[m][n]; //dp for(int i=0;i<n;i++){ f[0][i]=1; } for(int j=0;j<m;j++){ f[j][0]=1; } for(int i=1;i<m;i++){ for(int j=1;j<n;j++){ f[i][j]=f[i-1][j]+f[i][j-1]; } } return f[m-1][n-1]; }}
用滚动数组,改进的dp,占用空间更少。
public class Solution { public int uniquePaths(int m, int n) { int []f=new int[n]; f[0]=1; //dp for(int i=0;i<m;i++){ for(int j=1;j<n;j++){ f[j]=f[j-1]+f[j]; } } return f[n-1]; }}
dfs,对于大集合超时。
public class Solution { public int uniquePaths(int m, int n) { if(m<1 || n<1) return 0; if(m==1 && n==1) return 1; return uniquePaths(m-1,n)+uniquePaths(m,n-1); }}改进的dfs,可以过大集合。
public class Solution { public int [][]f; public int uniquePaths(int m, int n) { f=new int[m+1][n+1]; return dfs(m,n); } public int dfs(int m,int n){ if(m<1 || n<1) return 0; if(m==1 && n==1) return 1; return record(m-1,n)+record(m,n-1); } public int record(int x,int y){ if(f[x][y]>0) return f[x][y]; else return f[x][y]=dfs(x,y); }}
0 0
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- read 系统调用剖析 (vfs分析 address_space page cache)
- 随机为一维数组赋值,找出其中的第二大值
- 【菜鸟】 回忆初中及学编程中艰辛过程、感言
- c++对象模型
- String、StringBuffer与StringBuilder之间区别
- Unique Paths
- 逻辑卷镜像
- 几个画图的js插件
- hd 2029 Palindromes _easy version
- 不管是追求幸福也好
- 50_枚举类型
- 一个早晨,一名牧师正在准备第二天的讲道词
- 使用ClassFactory 生成渲染器
- 1.通过分类为数组添加一个倒序的一个方法. 比如: 数组中元素为 @”aa”, @”bb”, @”cc”, @”dd”, @”ee”, 倒序完之后为: @”ee”, @”dd”,@”cc”,@”bb