House Robber——LeetCode

时间:2022-01-15 03:06:38

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.

题目大意就是,要抢劫一条街,不能抢连续的两家,否则会报警,只能隔着抢或者跳着抢,输出可以抢到的最大值。这属于入门的动规题,可以理解为一个无上限的有限制的01背包题。

我的思路是:

  使用数组F[1...n]表示,抢劫到第i家时的最大获利为F[i],那么根据题意可以写出递推公式F[i]=max{F[i-1],F[i-2]+num[i]},其中num[i]是抢第i家可以获利多少。

下面是递归和非递归两种实现:

int[] max = new int[2000];

    public int rob(int[] num) {

        if (num == null || num.length == 0) {
return 0;
}
if (num.length == 1) {
return num[0];
}
if (num.length == 2) {
return Math.max(num[0], num[1]);
}
Arrays.fill(max, -1);
return choose(num.length - 1, num);
} public int choose(int k, int[] num) {
if (k == 0)
return num[k];
if (k < 0) {
return 0;
}
if (max[k] == -1) {
max[k] = Math.max(choose(k - 1, num), choose(k - 2, num) + num[k]);
}
return max[k];
}

非递归:

 public int rob2(int[] num) {

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