LeetCode 62. Unique Paths

Posted 皇家大鹏鹏

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

 

解答:

典型的动态规划问题,用一个矩阵来记录方法数量,每个数字表示从起始位置走到该位置有多少种方法。第一行和第一列均初始化为1,每一格数字更新结果为该格子上方和左方格子求和,表示我nums[i][j] = nums[i-1][j] + nums[i][j-1]。应该还有一些优化的方法,暂时先不讨论。

代码:

 1 class Solution {
 2 public:
 3     int uniquePaths(int m, int n) {
 4         vector<vector<int>> num(m, vector<int>(n, 1));
 5         for (int  i = 1; i < m; i++)
 6             for (int j = 1; j < n; j++)
 7                 num[i][j] = num[i - 1][j] + num[i][j-1];
 8         return num[m - 1][n - 1];
 9     }
10 };

时间复杂度:O(m*n)

空间复杂度:O(m*n)

以上是关于LeetCode 62. Unique Paths的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode.62-unique-paths

一天一道LeetCode#62. Unique Paths

Leetcode62 Unique Paths

Leetcode62 Unique Paths

leetcode 62. Unique Paths

leetcode62 Unique Paths