【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]就是狀態轉移方程,只有通過這個邏輯,才能把算法運轉起來。


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