美文网首页
62. Unique Paths/不同路径

62. Unique Paths/不同路径

作者: 蜜糖_7474 | 来源:发表于2019-05-31 11:21 被阅读0次

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

AC代码

class Solution {
public:
    int uniquePaths(int m, int n) {
        int a = m + n - 2, b = min(m, n) - 1, r = b;
        double ans = 1;
        for (int i = 0; i < r; ++i) {
            ans = ans * a / b;
            a -= 1;
            b -= 1;
        }
        return (int)(ans + 0.5);
    }
};

总结

如果用递归,那就是最基本的深搜,可惜会超时,但题目本身是个组合问题,一共会走m+n-2步,向下m-1,向右n-1;计算组合数即可

相关文章

网友评论

      本文标题:62. Unique Paths/不同路径

      本文链接:https://www.haomeiwen.com/subject/ayoitctx.html