力扣:198. 打家劫舍

 动态规划解法:

1.定义dp数组表示是下标+1间房偷窃到的最大金额

2.我们应该从后往前想向来进行递推公式的推导,前n个房屋偷的钱最大值等于前n-2个房屋偷的最大值加上第n个房屋的值 。   或者是  前n个房屋偷的钱最大值等于前n-1个房屋偷的最大值。

class Solution {
    public int rob(int[] nums) {
        int len=nums.length;
        //假如只有一间房
        if (len==1){
            return nums[0];
        }
        //假如有两间房
        if(len==2){
         return  Math.max(nums[0],nums[1]);
        }
        //定义dp数组表示是下标+1间房偷窃到的最大金额
        int [] dp=new int [len];
        //定义dp数组初始值
        dp[0]=nums[0];dp[1]=Math.max(nums[0],nums[1]);
        //遍历递推dp数组
      for(int i=2;i

你可能感兴趣的:(动态规划,leetcode,算法)