Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 房屋抢劫问题的动态规划子问题的解释?_Arrays_Algorithm_Data Structures_Dynamic Programming - Fatal编程技术网

Arrays 房屋抢劫问题的动态规划子问题的解释?

Arrays 房屋抢劫问题的动态规划子问题的解释?,arrays,algorithm,data-structures,dynamic-programming,Arrays,Algorithm,Data Structures,Dynamic Programming,我对理解动态规划中的子问题有一个疑问。例如: 问题陈述如下 You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security syst

我对理解动态规划中的子问题有一个疑问。例如:

问题陈述如下

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
输入是

nums = [1,2,3,1]
每个人都在使用的子问题关系是

dp[i] = Math.max(nums[i]+dp[i-2], dp[i-1])

谁能给我解释一下动态规划递推关系背后的逻辑。

基本上有3个条件

  • numHouse==0,moneySteal=0
  • numHouse==1,moneySteal=nums[0]//数组中只有一个元素
  • 现在有一个有趣的案例,强盗可以从彼此不相邻的房子里偷东西

    现在,在我的房子里,我们已经计算过了

    dp[i-1]: Max loot till i-1 house
    dp[i-2]: Max loot till i-2 house
    
    所以,强盗在i'th house有选择权

    如果强盗抢劫了i'th房子,这意味着它没有抢劫i-1房子,因为这两个房子相邻

    或者,强盗可以看到掠夺i'th house是否有益,因为掠夺i-1 house的价值将更高,由dp[i-1]表示

    因此,强盗通过检查哪一个更大(nums[i]+dp[i-2])来最大化第i个房子的掠夺量,即当dp[i-1]更大时,掠夺第i个房子还是不掠夺第i个房子

      dp[i] = Math.max(nums[i]+dp[i-2], dp[i-1])