C++實(shí)現(xiàn)LeetCode(62.不同的路徑)
[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
這道題讓求所有不同的路徑的個(gè)數(shù),一開始還真把博主難住了,因?yàn)橹昂孟駴]有遇到過這類的問題,所以感覺好像有種無從下手的感覺。在網(wǎng)上找攻略之后才恍然大悟,原來這跟之前那道 Climbing Stairs 很類似,那道題是說可以每次能爬一格或兩格,問到達(dá)頂部的所有不同爬法的個(gè)數(shù)。而這道題是每次可以向下走或者向右走,求到達(dá)最右下角的所有不同走法的個(gè)數(shù)。那么跟爬梯子問題一樣,需要用動(dòng)態(tài)規(guī)劃 Dynamic Programming 來解,可以維護(hù)一個(gè)二維數(shù)組 dp,其中 dp[i][j] 表示到當(dāng)前位置不同的走法的個(gè)數(shù),然后可以得到狀態(tài)轉(zhuǎn)移方程為: dp[i][j] = dp[i - 1][j] + dp[i][j - 1],這里為了節(jié)省空間,使用一維數(shù)組 dp,一行一行的刷新也可以,代碼如下:
解法一:
class 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]; } };
這道題其實(shí)還有另一種很數(shù)學(xué)的解法,實(shí)際相當(dāng)于機(jī)器人總共走了 m + n - 2步,其中 m - 1 步向右走,n - 1 步向下走,那么總共不同的方法個(gè)數(shù)就相當(dāng)于在步數(shù)里面 m - 1 和 n - 1 中較小的那個(gè)數(shù)的取法,實(shí)際上是一道組合數(shù)的問題,寫出代碼如下:
解法二:
class Solution { public: int uniquePaths(int m, int n) { double num = 1, denom = 1; int small = m > n ? n : m; for (int i = 1; i <= small - 1; ++i) { num *= m + n - 1 - i; denom *= i; } return (int)(num / denom); } };
到此這篇關(guān)于C++實(shí)現(xiàn)LeetCode(62.不同的路徑)的文章就介紹到這了,更多相關(guān)C++實(shí)現(xiàn)不同的路徑內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++產(chǎn)生隨機(jī)數(shù)的實(shí)現(xiàn)代碼
本篇文章是對C++中產(chǎn)生隨機(jī)數(shù)的實(shí)現(xiàn)代碼進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05c++實(shí)現(xiàn)簡單隨機(jī)數(shù)的代碼
在本篇文章里小編給大家整理的是一篇關(guān)于c++實(shí)現(xiàn)簡單隨機(jī)數(shù)的代碼內(nèi)容,有需要的朋友們可以跟著學(xué)習(xí)下。2021-05-05C語言編程C++柔性數(shù)組結(jié)構(gòu)示例講解
這篇文章主要介紹了C語言編程系列中的柔性數(shù)組,文中含有詳細(xì)的示例代碼講解,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-09-09C語言數(shù)組應(yīng)用實(shí)現(xiàn)掃雷游戲
這篇文章主要為大家詳細(xì)介紹了C語言數(shù)組應(yīng)用實(shí)現(xiàn)掃雷游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-06-06