198. 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.**

我的解决思路:这个问题跟矩阵连乘问题类似,所以我采用的是动规的方法来解决的,数组a[i][j],表示第i家到第j家最大的和,在这两层循环中,用k从i到j之间遍历,找到使a[i][j-1]的值最大的k的下标,k的值用一个变量flag保存着,如果k的下标==j-1,再比较a[i][j-2]+nums[j]和a[i][j-1]的值,如果k的下标!=j-1,说明此时可以最大的值为a[i][j-1]+nums[j]。

下面附上代码:

public class Solution {
    public int rob(int[] nums) {
        int n = nums.length;
        int[][] a = new int[n][n];
        if(n==0) return 0;
        for(int i=0;i<n;i++){
            for(int j=i;j<n;j++){
                if(i==j){
                    a[i][j]=nums[i];
                }
                else{
                    int max = a[i][i]+a[i][j];
                    int flag = i;
                    for(int k=i;k<=j;k++){
                        int temp = a[i][k]+a[k][j];
                        if(max<temp){
                            max = temp;
                            flag = k;
                        }
                    }
                    if(j-i<2){
                        a[i][j]=Math.max(nums[i],nums[j]);
                    }
                    else if(flag==j-1){
                        int temp1 = a[i][j-2]+nums[j];
                        if(temp1>a[i][j-1]){
                            a[i][j]=temp1;
                        }
                        else{
                            a[i][j]=a[i][j-1];
                        }
                    }
                    else{
                        a[i][j]=a[i][j-1]+nums[j];
                    }
                }
            }
        }
        return a[0][n-1];
    }
}

附上几组测试用例:
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值