【leetcode 动态规划 C++】198. House Robber

198. House Robber

【leetcode 动态规划 C++】198. House Robber

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

【leetcode 动态规划 C++】198. House Robber

class Solution {
public:
    int rob(vector<int>& nums) {
        if(nums.size() == 0) return 0;
        if(nums.size() == 1) return nums[0];
        vector<int> DP(nums.size(), 0);
        DP[0] = nums[0];
        DP[1] = nums[1];
        if(nums.size() > 2) DP[2] = nums[2] + nums[0];
        for(int ii = 3; ii < nums.size(); ii++) {
            DP[ii] = max(nums[ii] + DP[ii - 2], nums[ii] + DP[ii - 3]);
        }
        return max(DP[nums.size() - 1], DP[nums.size() - 2]);
    }
};
上一篇:House Robber


下一篇:Python爬虫系统化学习(4)