[] 62. Unique Paths LeetCode different paths (Medium) (JAVA)

[] 62. Unique Paths LeetCode different paths (Medium) (JAVA)

Topic Address: https://leetcode.com/problems/unique-paths/

Subject description:

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?

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

Constraints:

1 <= m, n <= 100
It's guaranteed that the answer will be less than or equal to 2 * 10 ^ 9.

Subject to the effect

A robot located in a left corner mxn grid (starting point figure below labeled "Start").

The robot can only move one step to the right or down. Robot trying to reach the bottom right corner of the grid (in the following figure labeled "Finish").

Q. How many different paths there are in total?

Problem-solving approach

This problem is actually with skills in mathematics.
1, mxn grid, the left needs to go m - 1 steps, need to go right n - 1 steps down a total of m + n - 2 Step
2, as long as the right to go to find the n - 1 m + n in step - 2-step how many cases you can: C m + n 2 n 1 C^{n - 1}_{m + n - 2}

class Solution {
    public int uniquePaths(int m, int n) {
        int min = m > n ? n : m;
        long res = 1;
        for (int i = 1; i <= min - 1; i++) {
            res = res * (m + n - 1 - i) / i;
        }
        return (int) res;
    }
}

When execution: 0 ms, defeated 100.00% of all users to submit in Java
memory consumption: 36.2 MB, beat the 5.01% of all users to submit in Java

Published 81 original articles · won praise 6 · views 2275

Guess you like

Origin blog.csdn.net/qq_16927853/article/details/104891761