首页 > 代码库 > 【Leetcode】Unique Paths

【Leetcode】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?

Note: m and n will be at most 100.

思路:同样可以使用动态规划方法解决,f(m,n) = f(m-1, n) + f(m, n-1)

代码一:

class Solution {
public:
    int uniquePaths(int m, int n) {
        
        if(m <= 0 || n <= 0)
            return 0;
        
        int result = 0;
        vector<vector<int>> counts;
        
        vector<int> temp;
        for(int i = 0; i < n; i++)
            temp.push_back(1);
        counts.push_back(temp);
        
        for(int i = 1; i < m; i++)
        {
            temp.clear();
            for(int j = 0; j < n; j++)
            {
                if(j == 0)  
                    temp.push_back(1);
                else
                    temp.push_back(temp[j - 1] + counts[i - 1][j]);
            }
            counts.push_back(temp);
        }
        
        return counts[m - 1][n - 1];
    }
};

代码二:

代码二比较巧妙,利用了本题的特殊性,即第一列的所有值都是1,只使用了一个数组即可。

// 动规,滚动数组
// 时间复杂度O(n^2),空间复杂度O(n)
class Solution {
public:
	int uniquePaths(int m, int n) {
		vector<int> f(n, 0);
		f[0] = 1;
		for (int i = 0; i < m; i++) {
			for (int j = 1; j < n; j++) {
				// 左边的f[j],表示更新后的f[j],与公式中的f[i][j] 对应
				// 右边的f[j],表示老的f[j],与公式中的f[i-1][j] 对应
				f[j] = f[j - 1] + f[j];
			}
		}
		return f[n - 1];
	}
};