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?

  方法一: DFS 大数据超时

class Solution {
public:
    void DFS(int i, int j, int m, int n){
        if( i== m && j == n){
            result++;
        }
        if(j+1 <= n) DFS(i, j+1,m,n);
        if(i+1 <= m) DFS(i+1,j,m,n);
    }
    int uniquePaths(int m, int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        result = 0;
        DFS(1,1,m,n);
        return result;
    }
private:
 int result;
};
View Code

  方法二:动态规划。 grid[i][j] = grid[i-1][j]+grid[i][j-1]

class Solution {
public:
    int uniquePaths(int m, int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<vector<int>> grid(m,vector<int>(n,0));
        for(int i = 0; i< n;i++) grid[0][i] = 1;
        for(int i = 0; i< m;i++) grid[i][0] = 1;
        
        for(int i = 1; i< m; i++)
            for(int j = 1; j < n; j++)
                    grid[i][j] = grid[i-1][j] + grid[i][j-1];
        return grid[m-1][n-1] ;
        
    }
};
原文地址:https://www.cnblogs.com/graph/p/3258531.html