LeetCode 62. 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?

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

Note: m and n will be at most 100.

 

1,自己解法

该问题可以转化为求组合数问题。一开始尝试迭代,但time out。尽量不要用乘除法,用时也要注意不要吞位。

int uniquePaths(int m, int n) {
    int min = -1;
    min = m>=n?n:m;
    int temp = min - 1;
    if(min == 1)
    {
        return 1;
    }
    int length = m + n - 2;
    double up = 1;
    double down = 1;
    for(int i = 0;i < min -1;i++)
    {
        up *= (double)(length - i);
        down *= (double)(temp - i);
    }
    return (int)(up/down);    
}

posted on 2018-03-06 10:19  米兰达莫西  阅读(129)  评论(0)    收藏  举报