Leetcode题解-198. House Robber

Leetcode题解-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.

题意

从一个非负整数序列中选择一组数使得和最大,不能选择相邻的两个数

思路

类似于01背包的思路,对每个数只有选和不选两种选择,因此动态方程是:
dp[0] = nums[0]
dp[1] = max{dp[0], nums[1]}
dp[i] = max{dp[i-1], dp[i-2] + nums[i]}

代码

class Solution {
public:
    int rob(vector<int>& nums) {
        int size = nums.size();
        if(size == 0) return 0;
        if(size == 1) return nums[0];
        int f[size];
        f[0] = nums[0]; 
        f[1] = (nums[0] < nums[1]) ? nums[1] : nums[0];
        for(int i = 2; i < size; i++){
            f[i] = (f[i-1] > f[i-2] + nums[i]) ? f[i-1] : f[i-2] + nums[i];
        }
        return f[size-1];
    }
};

你可能感兴趣的:(Leetcode)