62. Unique Paths

Posted lyinfo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了62. Unique Paths相关的知识,希望对你有一定的参考价值。

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 7 x 3 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

Example 1:

Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right

Example 2:

Input: m = 7, n = 3
Output: 28

  题目要求到达终点的可能路径,在已知长宽的情况下,到达途中Finish,一共要走(m - 1) + ( n - 1) = m + n - 2,其中向右m - 1步,向下n - 1步,很典型的排列组合问题,即在m + n - 2步中选 m - 1个位置向右走,剩下的自然是向下走,得到公式:

    N = C(m + n - 2, m - 1)

  编码完成组合公式的计算:

    public int uniquePaths(int m, int n) {
        return choose(m + n - 2, m > n ? n - 1 : m - 1);
    }

    public static int choose(int m, int n) {
        int member = 1;
        int temp = n;
        while (temp-- > 0) {
            member *= m--;
        }
        int denominator = 1;
        int start = 1;
        temp = n;
        while (temp-- > 0) {
            denominator *= start++;
        }
        return member / denominator;
    }

  提交后发现,在case : m = 10 , n = 10时,未通过。想了半天确定解题思路没问题,于是一步步debug,终于发现乘法计算中,超出了int能表示的最大整数!

 


以上是关于62. Unique Paths的主要内容,如果未能解决你的问题,请参考以下文章

62. Unique Paths

[leetcode] 62. Unique Paths

Leetcode 62. Unique Paths

LeetCode.62-unique-paths

62. Unique Paths

62. Unique Paths