LeetCode 62. Unique Paths (Medium)

来源:互联网 发布:菜鸟网络上市 编辑:程序博客网 时间:2024/06/06 12:54

题目描述:

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.

题目大意:从方格图的左上角开始,每次只能向右或向下走一格,问有多少种不同的路径走到右下角。

思路:一开始用dfs,结果超时了…想不到更好的解法,只能看网上的博客了。用DP,用一个m*n二维数组存路径(从(0, 0)到(i ,j))的数量。初始化数组每个元素为1,然后开始遍历:arr[i][j] = arr[i - 1][j] + arr[i][j - 1] (因为(i, j)只能从(i - 1, j)或(i, j - 1)转移过来),最后得到的arr[m - 1][n - 1](下标从0开始)即为路径总数。

c++代码:

class Solution {public:    int uniquePaths(int m, int n) {        vector<vector<int>> arr;        for (int i = 0; i < m; i++)        {            vector<int> temp;            for (int j = 0; j < n; j++)            {                temp.push_back(1);            }            arr.push_back(temp);        }        for (int i = 1; i < m; i++)        {            for (int j = 1; j < n; j++)            {                arr[i][j] = arr[i - 1][j] + arr[i][j - 1];            }        }        return arr[m - 1][n - 1];    }private:    int ans;};
原创粉丝点击