【leetcode 62】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 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

 解题思路

由于刚刚学习完动态规划的解题思路,便想着在leetcode上多刷几道动态规划的算法题。

本题题意很容易理解,就是只能向下或向右走,求起点到终点有多少条路径。那么下面就开始分析解题方法:

可以先在草稿纸上动手画一下,就会发现1*1的方格是没有路径的,当第一排或者第一列的所有路径都是1条

1*3

3*1

那么如果是n*n的方法,路线有多少种呢?

3*3

我们可以先找一下下规律,如果是n*m的矩阵,按照上面的发现,所有的(0,m)和(n,0)都是1条路径,那么(1,1)的路径条数有多少?

没错,是两条,它可以先向下走再向右走,也可以先向右走在向下走,这样的话就是2条路径。那么(2,1)有多少条路径呢?再次归纳可以发现它可以从(1,1)向右走或者从(2,0)向下走。那么(1,2),(2,2),(3,3)呢?

从以上归纳中可以发现,从(0,0)到(m,n)的路径条数和(m-1,n)还有(m,n-1)有关,重点的路径条数就是它左边一个点的路径条数加上上边一个点的路径条数之和,也就是F(m,n)=F(m-1,n)+F(m,n-1)。

代码实现

    public int uniquePaths(int m, int n) {
        int[][] dp = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                dp[i][j] = 0;
            }
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 || j == 0) {
                    dp[i][j] = 1;
                } else {
                    dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
                }
            }
        }
        return dp[m - 1][n - 1];
    }

总结

最后我们总结一下动态规划问题的解题思路

1、找到优化子问题,即对问题掰开进行分析,找到后一步的答案和前一步有什么规律可循。

2、写出边界值,找到子问题的规律之后,要确定最本质的子问题结果是多少,不然就成了一个解不出来的问题。

3、确定状态转移方程,也就是把第一步中子问题的规律用算法表达式表达出来,在本题中dp[i][j] = dp[i - 1][j] + dp[i][j - 1]就是状态转移方程,只有通过这个逻辑,才能把算法运转起来。


 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章