题目:
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?
求起点到终点的路径总数。
解法一:
深搜(超时)
public static int num=0;
public static int dir[][]={{1,0},{0,1}};
public int uniquePaths(int m, int n) {
int[][] map = new int[m][n];
map[0][0]=1;
dfs(m,n,map,0,0);
return num;
}
private void dfs(int m,int n,int map[][],int x,int y)
{
if(x==m-1 && y==n-1)
{
map[x][y]=0;
num++;
return ;
}
for(int i=0;i<2;i++)
{
int xx=x+dir[i][0];
int yy=y+dir[i][1];
if(xx>=0 && xx< m && yy>=0 && yy<n && map[xx][yy]!=1 )
{
map[xx][yy]=1;
dfs(m,n,map,xx,yy);
map[xx][yy]=0;
}
}
}
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);
}
解法二(缓存+深搜)
时间复杂度O(n*n) 空间复杂度O(n*n)
public class Solution {
public static int[][] dp = new int[102][102];
public int uniquePaths(int m, int n) {
dp[0][0]=1;
return dfs(m-1,n-1);
}
public int dfs(int m,int n)
{
if(m==0 && n==0) return dp[0][0];
if(m<0 || n<0) return 0;
if(dp[m][n]>0)
return dp[m][n];
else
return dp[m][n]=dfs(m-1,n)+dfs(m,n-1);
}
}
解法三(动态规划)
public class Solution {
public int uniquePaths(int m, int n) {
int[] dp = new int[n];
dp[0]=1;
for(int i=0;i<m;i++)
{
for(int j=1;j<n;j++)
{
dp[j]=dp[j]+dp[j-1];
}
}
return dp[n-1];
}
}
解法四 数学公式
一共有m+n-2次选择,有m-1(n-1)次选择向下(向右)走
public class Solution {
public int uniquePaths(int m, int n) {
return combination(m+n-2,Math.min(m-1, n-1));
}
//C n ^k
public int combination(int n,int k)
{
if(k==0) return 1;
if(k==1) return n;
long sum= factor(n,k+1);
System.out.println(factor(n-k,1));
sum/=factor(n-k,1);
return (int)sum;
}
public long factor(int n,int start)
{
long sum=1;
for(int i=start;i<=n;i++)
{
sum*=i;
}
return sum;
}
}