Leetcode62 Unique Paths

Unique Paths

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?
这里写图片描述

Solution1

  • 因为要到右下角,则必须先到其左边或者上边,从而将问题转化为一个子问题,可以用递归。(注意递归效率极低,有大量重复的运算)
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 uniquePaths3(m-1,n) + uniquePaths3(m,n-1);     
    }
}

Solution2

  • 从上可以看出这其实是一个动态递归问题,设置一个二维矩阵作为状态记录所用。
public class Solution {
    public int uniquePaths(int m, int n) {
        if(m<1||n<1) return 0;
        if(m==1||n==1) return 1;
        int[][] dp = new int[m][n];
        Arrays.fill(dp[0],1);
        for(int i=1;i<m;i++) dp[i][0] = 1;
        for(int i=1;i<m;i++){
            for(int j=1;j<n;j++){
                dp[i][j] = dp[i-1][j] + dp[i][j-1];
            }
        }
        return dp[m-1][n-1];        
    }
}

Solution3

  • 因为状态方程里面只与上一个状态有关,所以可以用滚动数组。
public class Solution {
    public int uniquePaths(int m, int n) {
        if(m<1||n<1) return 0;
        if(m==1||n==1) return 1;
        int[] dp = new int[n];
        Arrays.fill(dp,1);
        for(int i=1;i<m;i++){
            for(int j=1;j<n;j++){
                dp[j] += dp[j-1];
            }
        }
        return dp[n-1];       
    }
}

Solution4

  • 还有一种数学的方法来求解此题。效率更高。基本思路实际就是组合数学的内容,总共需要走的步数为(n+m-2)步,这些步中需要有(m-1)步是往下走的,所以问题就转化为了在这(n+m-2)步中选出(m-1)步,有多少种选法?
  • 这里要注意的是:在关于阶乘等相关的运算时,特别容易溢出,所以这里在计算的时候就直接相除了,并且先是用一个double类型的来存储。
public class Solution {
    public int uniquePaths(int m, int n) {
        if(m<1||n<1) return 0;
        if(m==1||n==1) return 1;
        double result = 1;//double类型存储所得商
        for(int i=1;i<m;i++) result = (result * (i+n-1) ) / i;
        return (int)result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值