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.

【题解】

这道题的本质相当于在一列数组中取出一个或多个不相邻数,使其和最大。这是一道动态规划问题。 

我们维护一个一位数组nMaxMoney,其中nMaxMoney[i]表示到i个房子时能形成的最大和。 

状态转移方程:

	nMaxMoney[0] = 0,i = 0
	nMaxMoney[1] = nums[0],i = 1
	nMaxMoney[i] = max(nums[i] + nMaxMoney[i - 2], nMaxMoney[i - 1]),i !=0 && i != 1

【代码】

    int rob(vector& nums) {
        int nSize = nums.size();
        if (nSize == 0)
            return 0;
        if (nSize == 1)
            return nums[0];
            
        vector nMaxMoney(nSize + 1, 0);
        nMaxMoney[0] = 0;
        nMaxMoney[1] = nums[0];
        for (int i = 2; i <= nSize; i++)
            nMaxMoney[i] = max(nMaxMoney[i - 2] + nums[i - 1], nMaxMoney[i - 1]);
            
        return nMaxMoney[nSize];
    }



你可能感兴趣的:(动态规划)