Memorization

  • 初始狀態不容易找到

  • 狀態轉移沒有順序性

337. House Robber III

Determine the maximum amount of money the thief can rob tonight without alerting the police.

Example 1:

Input: [3,2,3,null,3,null,1]

return 3+3+1=7

  • Use a map to do memorization in recursion

private Map<TreeNode, Integer> map = null;
public int rob(TreeNode root) {
    map = new HashMap<>();
    return helper(root);
}

private int helper(TreeNode node){
    if(node == null) return 0;

    if(map.containsKey(node)) return map.get(node);

    int val = node.val;

    if(node.left != null) val+=(helper(node.left.left)+helper(node.left.right));
    if(node.right != null) val+=(helper(node.right.left)+helper(node.right.right));

    int ans = Math.max(val, helper(node.left)+helper(node.right));
    map.put(node, ans);

    return ans;
}

Longest Continuous Increasing Subsequence 2D

Given an integer matrix (with row size n, column size m),find the longest increasing continuous subsequence in this matrix. (start at any row or column and go up/down/right/left any direction).

  • State: dp[i][j]: 以A[i][j]為出發點LCIS

Last updated

Was this helpful?