LeetCode 062 Unique Paths

来源:互联网 发布:新网域名管理系统 编辑:程序博客网 时间:2024/05/22 17:41
题目


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?

在一个m*n的点阵中,从左上角到右下角,每次只能向下或者向右。求最多有几种走法?


思路


1 这道题目可以用动态规划的方法来做,但是这里我用数学的方法来做(比较方便),后面一道用dp来做。

2 数学的方法可以这样考虑。m行,所以有m-1条向下的路可以选择。n列,所以有n-1的向右的路可以选择。总的来说,就是从m-1+n-1种方法中挑选出m-1中方法。 再简单点的模型,向下为1,向右为0,在一个2*3的点阵中,有一个解法为001,或者010,或者100。即求只有1个1和2个0的组合。

3 然后用java写这个函数的时候,要注意:

a 过程用long来做,防止溢出

b 先乘后除,防止整数除法截断




代码


public int uniquePaths2(int m, int n) {        if(m<n){        int temp=m;        m=n;        n=temp;        }        long ans=1;        m=m-1;        n=n-1;        for(int i=1;i<=n;i++){        ans=ans*(m+i)/i;        }        return (int)ans;            }




0 0
原创粉丝点击