mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
动态规划 不同路径 java 状态压缩优化
This commit is contained in:
@ -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
|
### Python
|
||||||
递归
|
递归
|
||||||
|
Reference in New Issue
Block a user