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).spa

How many possible unique paths are there?code


Above is a 7 x 3 grid. How many possible unique paths are there?blog

Note: m and n will be at most 100.it

Example 1:io

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:class

Input: m = 7, n = 3
Output: 28

 

解答:grid

典型的動態規劃問題,用一個矩陣來記錄方法數量,每一個數字表示從起始位置走到該位置有多少種方法。第一行和第一列均初始化爲1,每一格數字更新結果爲該格子上方和左方格子求和,表示我nums[i][j] = nums[i-1][j] + nums[i][j-1]。應該還有一些優化的方法,暫時先不討論。方法

代碼:im

 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)

相關文章
相關標籤/搜索