Leetcode House Robber II

本文提供了一种使用动态规划解决 LeetCode House Robber II 问题的方法,特别关注如何处理存在环的场景。通过详细解释算法逻辑和关键步骤,包括环状情况的特殊处理,以及给出复杂度分析,本文旨在帮助读者理解和实现这一解决方案。代码实例和测试验证了算法的有效性。
摘要由CSDN通过智能技术生成

Leetcode House Robber II 相关代码,本代码使用dp算法完成相关问题,本算法的关键为把存在环的退化成不带环的情况,在不带环的情况,用动态规化是相当容易的,以下是代码以及相关测试。算法复杂度为O(n)。

#include <iostream>
#include <vector>
using namespace std;

// the circumstance of circle can be divided into two case
// First: We choose the last, which means that the nearest two of it cannot be choose. And then
//        the max of it should be no_circle[1 --> i-2] + nums[i];
// Second: We doesn't choose the last, which means that nearest two of it can be choose or not.
//         And then, the max of it should be no_circle[0 --> i-1];
// And the result of the [0 --> i] with circle is the maximum of the former two condition.
class Solution {
public:
    int rob(vector<int>& nums) {
        if (nums.size() == 0) {
            return 0;
        }

        int len = nums.size();
        vector<vector<int> > max_longer(len, vector<int>(2, 0));
        max_longer[0][0] = nums[0];

        int max = nums[0];
        // preprocess the record before the common one
        if (len <= 3) {
            for (int i = 0; i < len; i ++) {
                max = max > nums[i]? max : nums[i];
            }
        } else {
            max_longer[1][0] = nums[0] > nums[1]? nums[0] : nums[1];
            max_longer[1][1] = nums[1];

            max_longer[2][0] = nums[0] + nums[2] > nums[1]? nums[0] + nums[2] : nums[1];
            max_longer[2][1] = nums[2] > nums[1]? nums[2] : nums[1];
        }

        for (int i = 3; i < len; i ++) {
            // for the max result
            int choose = nums[i] + max_longer[i - 2][1];
            int not_choose = max_longer[i - 1][0];
            max = choose > max? choose : max;
            max = not_choose > max? not_choose : max;

           // for the from 0 to i without circle max
           choose = nums[i] + max_longer[i - 2][0];
           not_choose = max_longer[i - 1][0];
           max_longer[i][0] = choose > not_choose? choose : not_choose;

           // for the from 1 to i without circle max
           choose = nums[i] + max_longer[i - 2][1];
           not_choose = max_longer[i - 1][1];
           max_longer[i][1] = choose > not_choose? choose : not_choose;
        }
        return max;
    }
};

int main(int argc, char * argv[]) {
    Solution so;
    vector<int> test(5, 0);
    test[0] = 1;
    test[1] = 5;
    int re = so.rob(test);
    cout<<"max:"<<re<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值