日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

[LeetCode]: 62: Unique Paths

發布時間:2025/6/15 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [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 3 x 7 grid. How many possible unique paths are there?

Note:?m?and?n?will be at most 100.

?

思路1:遞歸

終點的路徑數= 所有能達到終點的點的路徑數之和,即為:路徑[m][n] =?路徑[m-1][n] +?路徑[m][n-1]

依次遞歸,直到start點(0,0)

?

代碼:

public static int uniquePaths(int m, int n) {if(n == 1 && m==1){//初始的位置return 1;}else if(n == 1 && m>1){return uniquePaths(1,m-1);}else if(n >1 && m==1){return uniquePaths(n-1,1);}else{return uniquePaths(n-1,m)+uniquePaths(n,m-1);}}

?

結果在m=17 n=23的時候超時了。所以意識到題目的限制條件是需要速度!

?

思路2:動態規劃

某一個點的路徑數= 所有能達到該點的點的路徑數之和,即為:路徑[m][n] =?路徑[m-1][n] +?路徑[m][n-1]

與遞歸不同的是,遞歸是從大往小算,動態規劃是從小往大算

?

代碼如下:

public static int uniquePaths(int m, int n) {int[][] arrResult = new int[m][n];for(int i = 0;i<m;i++){for(int j = 0;j<n;j++){if(i == 0 && j== 0){ arrResult[0][0] = 1;}else if(i == 1 && j== 0){arrResult[1][0] = 1;}else if(i == 0 && j== 1){arrResult[0][1] = 1;}//以上是填充基礎值else{int row = 0;int column = 0;if(i> 0 ){row = arrResult[i-1][j];}if(j> 0 ){column = arrResult[i][j-1];}arrResult[i][j] = row + column; }}}return arrResult[m-1][n-1];}

?

轉載于:https://www.cnblogs.com/savageclc26/p/4871140.html

總結

以上是生活随笔為你收集整理的[LeetCode]: 62: Unique Paths的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。