[LeetCode] 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?


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-1 + n - 1, n-1)。计算的时候会用到阶层运算,因此要用longlong类型防止溢出,而且需要尽量先做除法运算。

class Solution {
public:
    int uniquePaths(int m, int n) {
        long long result = 1;
        if(m<=1 || n<=1){
            return result;
        }
        int j=n-1;
        for(int i=m+n-2; i>=m; i--){
            while(j>1 && result%j==0){
                result = result/j;
                j--;
            }
            result = result * i;
        }
        while(j>1 && result%j==0){
            result = result/j;
            j--;
        }
        return (int)result;
    }
};


0 条评论

    发表评论

    电子邮件地址不会被公开。 必填项已用 * 标注