[LeetCode] Unique Paths 不同的路徑

來源:互聯網
上載者:User

標籤:

 

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 不同的路徑

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.