[leetcode] 198. House Robber

来源:互联网 发布:java短链接实现 编辑:程序博客网 时间:2024/06/05 03:34

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.


本质是在一组数组中选取不相邻的元素,使其和最大。考虑是Dynamic Programming来解。维护一个数组dp,dp[i]代表到位置i时,不相邻元素的最大和。很容易得到一个递推公式:dp[i] = max(nums[i]+dp[i-2], dp[i-1]). dp的初始化使用nums[0]和nums[1]即可。

解法一:

class Solution {public:    int rob(vector<int>& nums) {        if (nums.size() == 0)            return 0;        else if (nums.size() == 1)            return nums[0];                    vector<int> dp = {nums[0],max(nums[0],nums[1])};        for(int i = 2; i < nums.size(); i++){            dp.push_back(max(nums[i]+dp[i-2],dp[i-1]));        }        return dp.back();    }};

或者考虑维护两个变量a和b,分别表示到奇偶位置的时候,不相邻元素之和最大。那么


解法二:

class Solution {public:    int rob(vector<int>& nums) {        int a = 0, b = 0;        for(int i = 0; i < nums.size(); i++){            if (i%2==0){                a = max(a + nums[i], b);            }else{                b = max(a, b + nums[i]);            }        }        return max(a,b);    }};



0 0
原创粉丝点击