动态规划_打家劫舍AK

198.打家劫舍

// 1.不可以盗窃相邻
// 2.状态转移 dp[i] = max(dp[i-1], num[i] + dp[i-2])
// 3.状态压缩呀 ~ dp_1, dp_2
// 似乎就解决了勒?
// 4. base case 一开始都是 0 
class Solution {
public:
    int rob(vector<int> &nums) {
        if(nums.size() == 0) return 0;
        int dp_i = 0;
        int dp_1 = 0, dp_2 = 0;
        for (int i = 0;i < nums.size(); i++) {
            dp_i = max(dp_1, nums[i] + dp_2);
            dp_2 = dp_1;
            dp_1 = dp_i;
        }
        return dp_i;
    }
};

213.打家劫舍 II

// 不就是加了个环嘛,这有啥?
// 咱们分两类
// 1. 0 ~ n-1
// 2. 1 ~ n
// 按照上一个算法跑两趟不久找到最大值了嘛
class Solution {
public:
    int robRange(vector<int>& nums,int start, int end) {
        int dp_i = 0;
        int dp_1 = 0, dp_2 = 0;
        for (int i = start; i < end; i++) {
            dp_i = max(dp_1, nums[i] + dp_2);
            dp_2 = dp_1;
            dp_1 = dp_i;
        }
        return dp_i;
    }
public:
    int rob(vector<int>& nums) {
        int n = nums.size();
        if(nums.size() == 0) return 0;
        if(nums.size() == 1) return nums[0];
        return max(robRange(nums, 0, n-1),
                   robRange(nums, 1, n));
    }
};

337.打家劫舍

//
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int rob(TreeNode root) {
        int[] res = dp(root);
        return Math.max(res[0], res[1]);
    }
    int[] dfs(TreeNode root) {
        if(root == null) return new int[]{0, 0};
        int[] left = dfs(root.left);
        int[] right = dfs(root.right);
        int rob = root.val + left[0] + right[0];
        int not_rob = Math.max(left[0], left[1]) 
                    + Math.max(right[0], right[1]);
        return new int[]{not_rob, rob};
    }
}
class Solution {
	Map<TreeNode, Integer> memo = new HashMap<>();
	public int rob(TreeNode root) {
		if (root == null) return 0;
		// 利用备忘录消除重叠子问题
		if (memo.containsKry(root)) return memo.get(root);
		// 抢,然后去下下家
		int do_it = root.val
			+ (root.left == null ? 0 : rob(root.left.left) + rob.(root.left.right))
			+ (root.right == null ? 0 : rob(root.right.left) + rob.(root.right.right));
		// 不抢,去下一家
		int not_do = rob(root.left) + rob(root.right);
		
		int res = Math.max(do_it, not_do);
		memo.put(root, res);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值