leetcode 198. House Robber(DP问题)

来源:互联网 发布:ionic lab mac百度云 编辑:程序博客网 时间:2024/05/16 17:18

问题描述:

  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[n];        int[] num2 = new int[n];        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]);    }}
原创粉丝点击