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 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

一、题目描述:

给定一个m*n的矩阵,让机器人从左上方走到右下方,只能往下和往右走,一共多少种走法。

二、解题方法:

//动态规划:
//设状态为f[i][j],表示从起点(1;1)到达(i; j)的路线条数,则状态转移方程为:
//f[i][j] = f[i-1][j] + f[i][j-1]
class Solution {
public:
	int uniquePaths(int m, int n) {
		vector<vector<int> > f(m, vector<int>(n, 1));
		for (int i = 1; i < m; i++)
			for (int j = 1; j < n; j++)
				f[i][j] = f[i - 1][j] + f[i][j - 1];
		return f[m - 1][n - 1];
	}
};

上面方法的空间复杂度较大为O(m*n),然而通过观察可以发现,我们每次更新f[i][j]只需要f[i-1][j](同一列)和f[i][j-1](左一列),所以只要保存当前列和左一列就行,而不是整个m*n矩阵,下面的代码可以将空间复杂度优化到O(min(m,n))

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

通过进一步的观察,我们还可以发现,上面程序中的pre[i]就是更新前的cur[i],所以可以进一步优化为:

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


最终优化空间程序为:

class Solution{
public:
	int uniquePaths(int m, int n) {
		if (m == 0 && n == 0)
			return 0;

		vector<int> dp(n, 1);
		for (int i = 1; i < m; i++)
			for (int j = 1; j < n; j++)
				dp[j] = dp[j - 1] + dp[j];

		return dp[n - 1];
	}
};


Leetcode 62: Unique Paths_第1张图片


你可能感兴趣的:(Leetcode 62: Unique Paths)