LeetCode 62. Unique Paths不同路径 (C++/Java)

题目:

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

Note: m and n will be at most 100.

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

分析:

简单说就是给一个m*n的网格,从左上角走到右下角,只能往下前进一格或往右前进一格,共有多少种走法。

到(m,n)格的路径数等于到(m-1,n)的路径数加上(m,n-1)的路径数,根据这个我们可以通过递推求得结果,机器人初始的位置路径数等于1,注意边界条件的判定,也可以将二维数组多开辟一行一列,用来跳过边界条件的处理,还可以先将第一行和第一列都初始化为1,再进行递推求解。

此外我们还可以通过递归求解此问题,即uniquePaths[m][n] = uniquePaths(m-1, n) + uniquePaths(m, n-1),只不过我们不是从起点求到终点,而是最先求右下角的路径数通过递归求解,同样也要注意递归终止条件。

程序:

C++

//Solution 1
class Solution {
public:
    int uniquePaths(int m, int n) {
        vector<vector<int>> res(m+1, vector<int>(n+1, 0));
        for(int i = 1; i < m+1; ++i){
            for(int j = 1; j < n+1; ++j){
                if(i == 1 && j == 1)
                    res[1][1] = 1;
                else
                    res[i][j] = res[i-1][j] + res[i][j-1];
            }
        }
        return res[m][n];
    }
};
//Solution 2
class Solution {
public:
    int uniquePaths(int m, int n) {
        if(m < 0 || n < 0) return 0;
        if(m == 1 && n == 1) return 1;
        if(res[m][n] > 0) return res[m][n];
        
        res[m][n] = uniquePaths(m-1, n) + uniquePaths(m, n-1);
        return res[m][n];
    }
 private:
     int res[101][101]={0};
};

Java

class Solution {
    public int uniquePaths(int m, int n) {
        int[][] res = new int[m+1][n+1];
        for(int i = 1; i < m+1; ++i)
            for(int j = 1; j < n+1; ++j){
                if(i == 1 && j == 1){
                    res[1][1] = 1;
                }
                else{
                    res[i][j] = res[i-1][j] + res[i][j-1];
                }
            }
        return res[m][n];
    }
}
class Solution {
    private int[][] res = new int[101][101];
    public int uniquePaths(int m, int n) {
        //int[][] res = new int[m+1][n+1];
        if(m < 0 || n < 0) return 0;
        if(m == 1 && n == 1) return 1;
        if(res[m][n] > 0) return res[m][n];
        
        res[m][n] = uniquePaths(m-1, n) + uniquePaths(m, n-1);
        return res[m][n];
    }
}
posted @ 2019-10-11 20:25  silentteller  阅读(246)  评论(0编辑  收藏  举报