算法:唯一路徑Unique Paths 動態規劃和二項係數解法

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?

在這裏插入圖片描述

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

Constraints:

1 <= m, n <= 100

It’s guaranteed that the answer will be less than or equal to 2 * 10 ^ 9.

1 動態規劃解法

動態規劃主要是找到跟上一條記錄聯繫的公式,這裏的公式就是path[i][j] = path[i-1][j] + path[i][j-1]。可以看下面的圖,

  1. 往下走的列path[i][0]都初始化爲1,表示一直往下有一種的解法;往右走的行path[0][j]都初始化爲1,表示一直往右有一種的解法。

  2. 再看第二列,當前位置的記錄是由上面的解法,和左邊的解法,加起來就是當前的解法。所以 2 = 1 + 1, 3 = 2 + 1. 以此類推。

  3. 結果是path[m-1][n-1], 因爲是從0開始計算的。
    在這裏插入圖片描述

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

2 二項係數解法Binomial coefficient

數學公式的解法,實際上先考慮一共要走多少步。比如Input: m = 7, n = 3,實際上是 m- 1 + n -1, 也就是8步。這就是表示有8個空要等着填。那麼有多少種填發呢,比如往下走表示D,往右走表示R,因爲二項係數解法,大小都是一樣的,爲了效率,用小的來解比較快。比如有2個R, 由於 (n - 1)。那麼第一個R可以放任意8個位置中的一個,第二個R可以放任意7個位置中的一個。因爲左邊(1, 2)和 (2, 1),都是放R的話是一樣的,所以就要除以二項係數的當前係數。

在這裏插入圖片描述

class Solution {
    public int uniquePaths(int m, int n) {
        int totalStep = m + n - 2;
        int change = (m > n ? n : m) - 1;
        double count = 1;
        for (int i = 1; i <= change; i++) {
          count = count * totalStep / i;
          totalStep--;
        }return (int)count;
    }
}

參考

https://www.youtube.com/watch?v=M8BYckxI8_U

https://leetcode.com/problems/unique-paths/

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