From 86ff0f2a35549d75d45ae873394514e812ab8436 Mon Sep 17 00:00:00 2001 From: yangzhaoMP Date: Wed, 6 Mar 2024 11:54:19 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=A8=E6=80=81=E8=A7=84=E5=88=92=20?= =?UTF-8?q?=E4=B8=8D=E5=90=8C=E8=B7=AF=E5=BE=84=20java=20=E7=8A=B6?= =?UTF-8?q?=E6=80=81=E5=8E=8B=E7=BC=A9=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0062.不同路径.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/problems/0062.不同路径.md b/problems/0062.不同路径.md index 207a66ee..32c64a12 100644 --- a/problems/0062.不同路径.md +++ b/problems/0062.不同路径.md @@ -285,6 +285,24 @@ public: } ``` +状态压缩 +```java +class Solution { + public int uniquePaths(int m, int n) { + // 在二维dp数组中,当前值的计算只依赖正上方和正左方,因此可以压缩成一维数组。 + int[] dp = new int[n]; + // 初始化,第一行只能从正左方跳过来,所以只有一条路径。 + Arrays.fill(dp, 1); + for (int i = 1; i < m; i ++) { + // 第一列也只有一条路,不用迭代,所以从第二列开始 + for (int j = 1; j < n; j ++) { + dp[j] += dp[j - 1]; // dp[j] = dp[j] (正上方)+ dp[j - 1] (正左方) + } + } + return dp[n - 1]; + } +} +``` ### Python 递归