**问题描述:
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];
}
}
附上几组测试用例: