【C++】【LeetCode】62. Unique Paths

来源:互联网 发布:大数据研究方向有哪些 编辑:程序博客网 时间:2024/06/15 08:44

题目

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?
m and n will be at most 100.

思路

其实就是一个排列组合的问题,mxn的矩形,其实就是向右走m-1步,向下走n-1步。即求Cmin(n1,m1)m1+n1

代码

class Solution {public:    int uniquePaths(int m, int n) {        if (m == 1 || n == 1) {            return 1;        }        if (m * n == 0) {            return 0;        }        int downNum = m - 1 + n - 1;        int upNum = min(n - 1, m - 1);        long result = 1;        for (int i = downNum; i > downNum - upNum; i--) {            result *= i;        }        for (int i = upNum; i > 1; i--) {            result /= i;        }        return result;    }};
原创粉丝点击