mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加(0337.打家劫舍III.md):增加typescript版本
This commit is contained in:
@ -429,7 +429,50 @@ const rob = root => {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### TypeScript
|
||||||
|
|
||||||
|
> 记忆化后序遍历
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const memory: Map<TreeNode, number> = new Map();
|
||||||
|
function rob(root: TreeNode | null): number {
|
||||||
|
if (root === null) return 0;
|
||||||
|
if (memory.has(root)) return memory.get(root);
|
||||||
|
// 不取当前节点
|
||||||
|
const res1: number = rob(root.left) + rob(root.right);
|
||||||
|
// 取当前节点
|
||||||
|
let res2: number = root.val;
|
||||||
|
if (root.left !== null) res2 += rob(root.left.left) + rob(root.left.right);
|
||||||
|
if (root.right !== null) res2 += rob(root.right.left) + rob(root.right.right);
|
||||||
|
const res: number = Math.max(res1, res2);
|
||||||
|
memory.set(root, res);
|
||||||
|
return res;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
> 状态标记化后序遍历
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function rob(root: TreeNode | null): number {
|
||||||
|
return Math.max(...robNode(root));
|
||||||
|
};
|
||||||
|
// [0]-不偷当前节点能获得的最大金额; [1]-偷~~
|
||||||
|
type MaxValueArr = [number, number];
|
||||||
|
function robNode(node: TreeNode | null): MaxValueArr {
|
||||||
|
if (node === null) return [0, 0];
|
||||||
|
const leftArr: MaxValueArr = robNode(node.left);
|
||||||
|
const rightArr: MaxValueArr = robNode(node.right);
|
||||||
|
// 不偷
|
||||||
|
const val1: number = Math.max(leftArr[0], leftArr[1]) +
|
||||||
|
Math.max(rightArr[0], rightArr[1]);
|
||||||
|
// 偷
|
||||||
|
const val2: number = leftArr[0] + rightArr[0] + node.val;
|
||||||
|
return [val1, val2];
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### Go
|
### Go
|
||||||
|
|
||||||
```go
|
```go
|
||||||
// 打家劫舍Ⅲ 动态规划
|
// 打家劫舍Ⅲ 动态规划
|
||||||
// 时间复杂度O(n) 空间复杂度O(logn)
|
// 时间复杂度O(n) 空间复杂度O(logn)
|
||||||
|
Reference in New Issue
Block a user