Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

leetcode 198.打家劫舍 #动态规划 #11

Open
Anonymity94 opened this issue May 27, 2022 · 1 comment
Open

leetcode 198.打家劫舍 #动态规划 #11

Anonymity94 opened this issue May 27, 2022 · 1 comment

Comments

@Anonymity94
Copy link

Anonymity94 commented May 27, 2022

image

推导递推公式:

  • 如果偷第 i 房间,那么dp[i] = dp[i - 2] + nums[i] ,即:第 i-1 房一定是不考虑的,找出 下标 i-2(包括 i-2)以内的房屋,最多可以偷窃的金额为 dp[i-2] 加上第 i 房间偷到的钱
  • 如果不偷第 i 房间,那么 dp[i] = dp[i - 1],即考虑 i-1 房

递推完成后,数组的最后一项便可以得到答案。

/**
 * @param {number[]} nums
 * @return {number}
 */
var rob = function (nums) {
  const dp = new Array(nums.length).fill(0);
  // dp[i] 表示到下标为i的房屋时,能偷盗的最高金额
  dp[0] = nums[0];
  // 长度可能为1,所以保护一下,给个默认值0
  dp[1] = Math.max(nums[0], nums[1] || 0);

  for (let i = 2; i < nums.length; i++) {
    // 偷第i个房屋:dp[i - 2] + nums[i]
    // 不偷第i个房屋:这时候金额等于上次偷盗的金额
    dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]);
  }

  return dp.at(-1);
};
@webVueBlog
Copy link
Member

198. 打家劫舍

/*
 * @lc app=leetcode.cn id=198 lang=javascript
 *
 * [198] 打家劫舍
 */

// @lc code=start
/**
 * @param {number[]} nums
 * @return {number}
一夜之内偷窃的最高金额,相邻房屋不能偷
dp[i] = max ? 到某一天,偷窃的最高的金额

i=5
dp[5] = dp[4](可能第四天偷) / dp[3](第3天偷,第4天不偷) + nums[5]
dp[5] = dp[4] / dp[3] + nums[5]
dp[i] = Math.max(dp[i-1], dp[i-2] + nums[i])
边界情况:
dp[0] // -1 -2
dp[0] dp[1] // 从2开始
(56 ms)
 */
var rob = function(nums) {
 let len = nums.length;
 let dp = new Array();
 dp[-1] = dp[-2] = 0;
 // 遍历
 for(let i = 0; i < nums.length; i++) {
  dp[i] = Math.max(dp[i-1], dp[i-2] + nums[i])
 }
 return dp[len - 1]
};
// @lc code=end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants