Unique Paths

来源:互联网 发布:淘宝怎么提高店铺权重 编辑:程序博客网 时间:2024/06/09 13:41
Problem:

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?

Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

这个问题实质就是求组合数C(m+n-2,m-1)。
用组合数公式C(n,k)=C(n,k-1)*(n-k+1)/k。
因为C(n,k)=C(n,n-k),所以选择min(m-1,n-1)做为公式中的k能够减少迭代计算次数。注意把乘法运算转换为long防止中间结果溢出。
Solution:
public class Solution {
    public int uniquePaths(int m, int n) {
        if(m<=0||n<=0)
             return 0;
        int p = Math.min(m-1, n-1),q = m+n-2;
        int tmp = 1;
        for(int k=1;k<=p;k++)
        {
             tmp = (int)((long)(q-k+1)*tmp/k);
        }
        return tmp;
    }
}
0 0
原创粉丝点击