【LeetCode】198. House Robber

    xiaoxiao2021-12-10  8

    题目: 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. 分析: 简单的动态规划问题。在一个数组中取出不相邻的且和最大的数。 状态转移方程为:sum[i] = max{sum[i-1],sum[i-2]+num[i]}。 代码:

    class Solution { public: int rob(vector<int>& nums) { int l = nums.size(); int tag = 0; if(l == 0) return 0; int sum[3]; for(int i = 0;i<3;i++) sum[i] = 0; for(int i = 0;i<l;i++) { sum[2] = sum[0]+nums[i]; if(sum[2]<sum[1]) { sum[2] = sum[1]; } sum[0] = sum[1]; sum[1] = sum[2]; } return sum[2]; } };
    转载请注明原文地址: https://ju.6miu.com/read-700322.html

    最新回复(0)