mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
Merge branch 'youngyangyang04:master' into master
This commit is contained in:
@ -232,6 +232,38 @@ class Solution:
|
|||||||
return dp[-1][-1]
|
return dp[-1][-1]
|
||||||
```
|
```
|
||||||
|
|
||||||
|
```python
|
||||||
|
class Solution:
|
||||||
|
"""
|
||||||
|
使用一维dp数组
|
||||||
|
"""
|
||||||
|
|
||||||
|
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
|
||||||
|
m, n = len(obstacleGrid), len(obstacleGrid[0])
|
||||||
|
|
||||||
|
# 初始化dp数组
|
||||||
|
# 该数组缓存当前行
|
||||||
|
curr = [0] * n
|
||||||
|
for j in range(n):
|
||||||
|
if obstacleGrid[0][j] == 1:
|
||||||
|
break
|
||||||
|
curr[j] = 1
|
||||||
|
|
||||||
|
for i in range(1, m): # 从第二行开始
|
||||||
|
for j in range(n): # 从第一列开始,因为第一列可能有障碍物
|
||||||
|
# 有障碍物处无法通行,状态就设成0
|
||||||
|
if obstacleGrid[i][j] == 1:
|
||||||
|
curr[j] = 0
|
||||||
|
elif j > 0:
|
||||||
|
# 等价于
|
||||||
|
# dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
|
||||||
|
curr[j] = curr[j] + curr[j - 1]
|
||||||
|
# 隐含的状态更新
|
||||||
|
# dp[i][0] = dp[i - 1][0]
|
||||||
|
|
||||||
|
return curr[n - 1]
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
|
||||||
|
@ -368,6 +368,20 @@ func mergeTrees(t1 *TreeNode, t2 *TreeNode) *TreeNode {
|
|||||||
Right: mergeTrees(t1.Right,t2.Right)}
|
Right: mergeTrees(t1.Right,t2.Right)}
|
||||||
return root
|
return root
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 前序遍历简洁版
|
||||||
|
func mergeTrees(root1 *TreeNode, root2 *TreeNode) *TreeNode {
|
||||||
|
if root1 == nil {
|
||||||
|
return root2
|
||||||
|
}
|
||||||
|
if root2 == nil {
|
||||||
|
return root1
|
||||||
|
}
|
||||||
|
root1.Val += root2.Val
|
||||||
|
root1.Left = mergeTrees(root1.Left, root2.Left)
|
||||||
|
root1.Right = mergeTrees(root1.Right, root2.Right)
|
||||||
|
return root1
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
JavaScript:
|
JavaScript:
|
||||||
|
Reference in New Issue
Block a user