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
原创粉丝点击