標籤:
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.
這道題讓求所有不同的路徑的個數,一開始還真把我難住了,因為之前好像沒有遇到過這類的問題,所以感覺好像有種無從下手的感覺。在網上找攻略之後才恍然大悟,原來這跟之前那道 Climbing Stairs 爬梯子問題 很類似,那道題是說可以每次能爬一格或兩格,問到達頂部的所有不同爬法的個數。而這道題是每次可以向下走或者向右走,求到達最右下角的所有不同走法的個數。那麼跟爬梯子問題一樣,我們需要用動態規劃Dynamic Programming來解,我們可以維護一個二維數組dp,其中dp[i][j]表示到當前位置不同的走法的個數,然後可以得到遞推式為: dp[i][j] = dp[i - 1][j] + dp[i][j - 1],這裡為了節省空間的,我們使用一位元組dp,一行一行的重新整理也可以,代碼如下:
解法一
// DPclass Solution {public: int uniquePaths(int m, int n) { vector<int> dp(n, 1); for (int i = 1; i < m; ++i) { for (int j = 1; j < n; ++j) { dp[j] += dp[j - 1]; } } return dp[n - 1]; }};
這道題其實還有另一種很數學的解法,參見網友Code Ganker的部落格,實際相當於機器人總共走了m + n - 2步,其中m - 1步向下走,n - 1步向右走,那麼總共不同的方法個數就相當於在步數裡面m - 1和n - 1中較小的那個數的取法,實際上是一道組合數的問題,寫出代碼如下:
解法二
class Solution {public: int uniquePaths(int m, int n) { double num = 1; double denom = 1; int small = m > n ? n : m; int big = m > n ? m : n; for (int i = 1; i <= small - 1; ++i) { num *= m + n - 1 - i; denom *= i; } return (int)(num / denom); }};
[LeetCode] Unique Paths 不同的路徑