62. Unique Paths

Difficulty:
Related Topics:
Similar Questions:

Problem

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

Solution

/**
 * @param {number} m
 * @param {number} n
 * @return {number}
 */
var uniquePaths = function(m, n) {
  var dp = Array(m);
  if (!m || !n) return 0;
  for (var i = 0; i < m; i++) {
    dp[i] = Array(n);
    for (var j = 0; j < n; j++) {
      if (j > 0 && i > 0) dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
      else if (j > 0 && i === 0) dp[i][j] = dp[i][j - 1];
      else if (j === 0 && i > 0) dp[i][j] = dp[i - 1][j];
      else dp[i][j] = 1;
    }
  }
  return dp[m - 1][n - 1];
};

Explain:

dp[i][j] 代表到达该点的路径数量。该点可以从左边点或上边点到达 也就是 dp[i][j] = dp[i - 1][j] + dp[i][j - 1]

Complexity:

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy