House Robber

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

题意是:

n个商店,每个商店都有一定的现钞,但是又由于相邻的商店同时被抢会被警察知道而被逮捕。假如自己是一个很有经验的抢劫犯,那么现在要决定抢劫这个n个商店,要求抢的金额最大,同时不能被警察逮捕。

由于刚看了DP解决0-1背包问题,所以感觉还是比较简单的。

主要是找到一个状态转移方程。

 

public class Solution {

    public int rob(int[] num) {

        //设F[j] 表示抢劫前j个商店的总金额

        //假设第j-1个商店没有被抢,则F[j]=F[j-1]+num[j]

        //假设第j-1个商店被抢了,则F[j]=max{F[j-1],F[j-2]+num[j]}

        if(num.length == 0){

            return 0;

        }

        if(num.length == 1){

            return num[0];

        }

        if(num.length == 2){

            return num[0]>num[1]?num[0]:num[1];

        }

        int[] F = new int[num.length];

        boolean[] robbed = new boolean[num.length];

        F[0] = num[0];

        robbed[0] = true;

        F[1] = num[0]>num[1] ? num[0] : num[1];

        robbed[1] = num[0] > num[1] ? false : true;

        int count = 2;

        while(count < num.length){

            if(!robbed[count-1]){//第count-1个商店没有被抢

                F[count] = F[count-1]+num[count];

                robbed[count] = true;

            }else{//第count-1个商店被抢了

                if(F[count-1] >= F[count-2] + num[count]){

                    F[count] = F[count - 1];

                    robbed[count] = false;

                }else{

                    F[count] = F[count-2] + num[count];

                    robbed[count] = true;

                    robbed[count - 1] = false;

                }

            }

            count ++;

        }

        return F[num.length-1];

    }

}

 

你可能感兴趣的:(r)