1. 程式人生 > >Leetcode演算法Java全解答--62. 不同路徑

Leetcode演算法Java全解答--62. 不同路徑

Leetcode演算法Java全解答–62. 不同路徑

文章目錄

題目

一個機器人位於一個 m x n 網格的左上角 (起始點在下圖中標記為“Start” )。

機器人每次只能向下或者向右移動一步。機器人試圖達到網格的右下角(在下圖中標記為“Finish”)。

問總共有多少條不同的路徑?

例如,上圖是一個7 x 3 的網格。有多少可能的路徑?

說明:m 和 n 的值均不超過 100。

示例 1:

輸入: m = 3, n = 2
輸出: 3
解釋:
從左上角開始,總共有 3 條路徑可以到達右下角。
1. 向右 -> 向右 -> 向下
2. 向右 -> 向下 -> 向右
3. 向下 -> 向右 -> 向右
示例 2:

輸入: m = 7, n = 3
輸出: 28

想法

和第70題走樓梯類似,不過這個是二維的,那個是直線的

任何一格位置資料都是通過 他左邊一格的資料+上邊的資料來的。

比如(7,3)座標的資料,是通過(6,3) + (7,2)獲取到的結果

那麼同理可得(6,3)又是根據(5,3)+(6,2)來的,

同理可得(7,2)又是根據(7,1)+(6,2)來的,

這樣就能往前推到(1,1)了,這裡就是邊界條件

這裡注意一下,(6,3)和(7,2)都用到了(6,2)的結果,如果每次都去計算(6,2)的值,很浪費時間,

所以我們用一個hashMap儲存資料,key就是(6,2),value就是(6,2)的值

結果

超過5.74%的測試案例

時間複雜度/空間複雜度: n/n

總結

程式碼

我的答案

 HashMap hashMap = new HashMap<String, Integer>();

  public int uniquePaths(int m, int n) {
    return recuResult(m, n);
  }

  public int recuResult(int m, int n) {
    int result = 0;
    if (m == 0 || n == 0) {
      return 0;
    }

    if (m == 1 && n == 1) {
      return 1;
    }

    if (hashMap.get(m + "+" + n) != null) {
      return (Integer) hashMap.get(m + "+" + n);
    }

    result = recuResult(m - 1, n) + recuResult(m, n - 1);
    hashMap.put(m + "+" + n, result);
    return result;
  }

大佬們的答案

  /**************************************
   * 比我好的答案 better
   * 這個直接用陣列求解,速度比我快
   * ***********************************/
  public int better(int m, int n) {
    if (m <= 0 || n <= 0) {
      return 0;
    }
    int[][] dp = new int[m][n];
    dp[0][0] = 1;
    for (int i = 1; i < n; i++) {
      dp[0][i] = 1;
    }
    for (int i = 1; i < m; i++) {
      dp[i][0] = 1;
    }
    for (int i = 1; i < m; i++) {
      for (int j = 1; j < n; j++) {
        dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
      }
    }
    return dp[m - 1][n - 1];
  }

測試用例


@Test
public void test062() {
    // 建立測試案例
    int m1 = 3;
    int n1 = 2;
    int m2 = 7;
    int n2 = 3;

    // 測試案例期望值
    int expResult1 = 3;
    int expResult2 = 28;

    // 執行方法
    Solution062 solution062 = new Solution062();
    int result1 = solution062.uniquePaths(m1,n1);
    int result2 = solution062.uniquePaths(m2,n2);

    // 判斷期望值與實際值
    Assert.assertEquals(expResult1, result1);
    Assert.assertEquals(expResult2, result2);

}

其他

程式碼託管碼雲地址:https://gitee.com/lizhaoandroid/LeetCodeAll.git

檢視其他內容可以點選專欄或者我的部落格哈:https://blog.csdn.net/cmqwan

“大佬們的答案” 標籤來自leetcode,侵權請聯絡我進行刪改

如有疑問請聯絡,聯絡方式:QQ3060507060