Leetcode__198_rob_강도질
                                            
 14092 단어  Letcode 퀴즈의 동태적 기획leetcode
                    
한 무리의 주민을 약탈하지만 이웃의 주민을 약탈해서는 안 되며 최대 강도량을 구할 수 없다.
해결 방법 및 코드:
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));
    }
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Leetcode_62_uniquePaths_행렬의 총 경로package DP; public class _62_uniquePaths { //1. dp public int uniquePaths(int m, int n){ int[][] dp = new int[m][n]; for...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.