码迷,mamicode.com
首页 > 其他好文 > 详细

62. Unique Paths

时间:2018-06-02 19:06:01      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:path   cat   技术   otto   ems   mem   AC   etc   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 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

标签:path   cat   技术   otto   ems   mem   AC   etc   leetcode   

原文地址:https://www.cnblogs.com/lyInfo/p/9126230.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!