美文网首页
198. House Robber I and II

198. House Robber I and II

作者: becauseyou_90cd | 来源:发表于2018-07-20 07:45 被阅读0次

    https://leetcode.com/problems/house-robber/description/

    解题思路:

    1. 计算当前index的sum值

    代码如下:
    class Solution {
    public int rob(int[] nums) {

        if(nums == null || nums.length == 0) return 0;
        int len = nums.length;
        if(len == 1) return nums[0];
        else if(len == 2) return Math.max(nums[0], nums[1]);
        int[] dp = new int[len];
        dp[0] = nums[0]; dp[1] = Math.max(nums[0], nums[1]);
        for (int i = 2; i < len; i++){
            dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]);
        }
        return dp[len - 1];            
    }
    

    }

    https://leetcode.com/problems/house-robber-iii/description/
    解题思路:

    1. 计算当前index的sum值,然后比较array最后index和index-1的sum值就好了
      class Solution {
      public int rob(int[] nums) {

       int len = nums.length;
       if(len <= 0) return 0;
       else if(len == 1) return nums[0];
       else if(len == 2) return Math.max(nums[0],nums[1]);
       int[] forward = new int[len];
       int[] back = new int[len];
       forward[0] = nums[0]; forward[1] = Math.max(nums[0],nums[1]);
       back[1] = nums[1]; back[2] = Math.max(nums[1],nums[2]);
       for(int i = 2; i < len - 1; i++){
           forward[i] = Math.max(forward[i-1], forward[i-2] + nums[i]);
       }
       for(int i = 3; i < len; i++){
           back[i] = Math.max(back[i-1], back[i-2] + nums[i]);
       }
       return Math.max(forward[len - 2], back[len-1]);
      

      }
      }

    相关文章

      网友评论

          本文标题:198. House Robber I and II

          本文链接:https://www.haomeiwen.com/subject/dpxfmftx.html