zoukankan      html  css  js  c++  java
  • LeetCode "House Robber II"

    A high quality DP problem to work on. It is not an merely educational DP, it is subtle.

    Basic ideas:
      1. Run original DP twice, 1st with num[0] selected, 2nd with num[0] not selected
      2. Since it is circular arrangement, if 1st is assumed to be selected, we should not consider the last element

    class Solution {
    public:
        int _rob(vector<int> &num) {
            size_t len = num.size();
    
            int inc = num[0];
            int exc = 0;
            for (int i = 1; i < len - 1; i++) // Note: we skipped the last element
            {
                int old_inc = inc;
                inc = num[i] + exc;
                exc = std::max(exc, old_inc);
            }
    
            return std::max(inc, exc);
        }
    
        int rob(vector<int> &num) {
            size_t len = num.size();
            if (len == 0) return 0;
    
            // num[0] is selected
            int rob1 = _rob(num);
    
            // num[0] is not selected
            vector<int> in2;
            in2.insert(in2.end(), num.begin() + 1, num.end());
            in2.push_back(num[0]);
            int rob2 = _rob(in2);
            
            return std::max(rob1, rob2);
        }
    };
  • 相关阅读:
    python列表[]中括号
    python元组()小括号
    python break continue跳过和跳出循环
    python FOR循环
    python while循环
    python if elif else判断语句
    python使用变量
    python -input用户输入
    pycharm模板
    港股收费
  • 原文地址:https://www.cnblogs.com/tonix/p/4516624.html
Copyright © 2011-2022 走看看