Leetcode__198_rob_强盗抢劫

题目描述:

抢劫一排住户,但是不能抢邻近的住户,求最大抢劫量。

解决思路和代码:

package DP;

import java.util.Arrays;

/**
 * 强盗抢劫
 * Find recursive relation
 * Recursive (top-down)
 * Recursive + memo (top-down)
 * Iterative + memo (bottom-up)
 * Iterative + N variables (bottom-up)
 */
public class _198_rob {
     
    // 1. Recursive (top-down)

    /**
     * 选择rob当前i:则nums[i-2] + nums[i]
     * 不选择当前i:则nums[i-1]
     */
    private static int rob1(int[] nums, int i){
     
        if (i < 0){
     
            return 0;
        }
        return Math.max(rob1(nums, i-2) + nums[i], rob1(nums, i-1));
    }
    public static int rob1(int[] nums){
     

        return rob1(nums, nums.length-1);
    }

    //2. Recursive + memo (top-down)(备忘录法去除重复值)
    public static int rob2(int[] nums){
     
        int n = nums.length;
        int[] mem = new int[n+1];
        Arrays.fill(mem, -1);
        return  rob2(nums, n-1, mem);
    }
    private static int rob2(int[] nums, int i, int[] mem){
     
        if (i < 0){
     
            return 0;
        }
        if (mem[i] >= 0){
     
            return mem[i];
        }
        int res = Math.max(rob1(nums, i-2) + nums[i], rob1(nums, i-1));
        mem[i] = res;
        return res;
    }

    /**
     * 3. 动态规划(bottom-top)
     */
    public static int rob(int[] nums){
     
        int n = nums.length;
        int[] dp = new int[n];
        dp[0] = nums[0];
        dp[1] = Math.max(nums[0], nums[1]);
        for (int i = 2; i < n; i++){
     
            dp[i] = Math.max(dp[i-2] + nums[i], dp[i-1]) ;
        }
        return dp[n-1];
    }

    public static void main(String[] args) {
     
        int[] nums = {
     2, 7, 9, 3, 1};
        int[] nums2 = {
     2, 1, 1, 2};
        System.out.println(rob2(nums2));
    }
}

你可能感兴趣的:(Leetcode刷题之动态规划,leetcode)