您的位置:首页 > 其它

leetcode 198. House Robber(DP问题)

2017-12-20 20:01 537 查看
问题描述:

  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.

思路:

  利用动态规划

代码:

class Solution {
public int rob(int[] nums) {
if(nums == null || nums.length == 0) return 0;
int n = nums.length;
int[] num1 = new int
;
int[] num2 = new int
;
num1[0] = nums[0];
num2[0] = 0;
for(int i = 1; i<n; i++){
num1[i] = num2[i-1] + nums[i];
num2[i] = Math.max(num1[i-1], num2[i-1]);
}

return Math.max(num1[n-1], num2[n-1]);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: