leetcode62 - Unique Paths - medium

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.

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.
 
如果用一个二维数组,dp[i][j]记录number of unique paths to arrive at the point (i, j),那么space complexity是O(m*n),
这里可以有一个优化,因为每次操作我们只会用到当前行和前一行,那用两个一维数组就够了,只对cur这个数组进行更新,操作完到下一行的时候,swap它们,后续要用到的数据就在prev里,cur里的数据继续被覆盖,直到扫完整个grid,最后返回的是prev[n-1],space complexity可以到O(n)。
 
实现:
class Solution {
public:
    int uniquePaths(int m, int n) {
        
        vector<vector<int>> dp(m, vector<int>(n, 0));
        
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 || j == 0) dp[i][j] = 1;
                else dp[i][j] = dp[i-1][j] + dp[i][j-1];
            }
        }
        return dp[m-1][n-1];
        
    }
};

 

优化:

class Solution {
public:
    int uniquePaths(int m, int n) {
        
        vector<int> pre(n, 1), cur(n, 0);
        cur[0] = 1;
        
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                cur[j] = pre[j] + cur[j-1];
            }
            swap(pre, cur);
        }
        return pre[n-1];
        
    }
};

 

 

posted @ 2020-08-04 12:07  little_veggie  阅读(84)  评论(0)    收藏  举报