[LeetCode]House Robber II

思路和House Robber很像,唯一不同在于当从0开始算的时候,最后的一个房间是一定不可以抢的,所以我们分别算从0和从1开始的,取其中最大值

public class Solution {
    public int rob(int[] nums) {
        int length = nums.length;
        if (length == 0) {
            return length;
        } else if (length == 1) {
            return nums[0];
        }
        if (length == 2) {
            return helper(nums, 0);
        }
        return Math.max(helper(nums, 0), helper(nums, 1));
    }
    public int helper(int[] nums, int start) {
        int length = nums.length;
        int[] record = new int[length];
        record[start] = nums[start];
        record[start + 1] = nums[start + 1];
        int result = Math.max(record[start], record[start + 1]);
        for (int i = start + 2; i < length; i++) {
            if (i == length - 1 && start == 0) {
                break;
            }
            int tmp1 = record[i - 2];
            int tmp2 = i > 2 ? record[i - 3] : 0;
            record[i] = nums[i] + Math.max(tmp1, tmp2);
            result = Math.max(record[i], result);
        }
        return result;
    }
}

  

posted @ 2015-11-27 04:38  Weizheng_Love_Coding  阅读(135)  评论(0编辑  收藏  举报