leetcode题目例题解析(九)

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?
这里写图片描述
Above is a 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.

题意解析:

这道题目就是算从左上角到右下角有多少种不同的路线,然后,移动的方式只有两种,一种是向右,一种是向下

解题思路:

每次移动到一个方格,都有两种可能的方式,一种是从上面下来,另一种是从左边过来,然后到达这个方格的路径的数目是到达上面方格的数目加上到达左边方格数目的和。这样就可以建立后面的结果和前面结果之间的联系。

代码:

class Solution {
public:
    int uniquePaths(int m, int n) {
        int **mat = new int*[m];
        for (int i = 0; i < m; i++)
            mat[i] = new int[n];
        mat[0][0] = 1;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i|j) {
                    mat[i][j] = 0;
                    if (i - 1 >= 0) {
                        mat[i][j] += mat[i-1][j];
                    }
                    if (j - 1 >= 0) {
                        mat[i][j] += mat[i][j-1];
                    }
                }
            }
        }
        int ans = mat[m-1][n-1];
        for (int i = 0; i < m; i++)
            delete[] mat[i];
        delete[] mat;
        return ans;
    }

};

注:本题目也可以用递归的方法去做,但是如果用递归,会导致递归的深度过大,容易发生栈溢出的错误,所以再给出数据比较大的情况下,尽量选择非递归的算法

原题目链接:
https://leetcode.com/problems/unique-paths/description/

猜你喜欢

转载自blog.csdn.net/OzhangsenO/article/details/78466820