标签:
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); } };
标签:
原文地址:http://www.cnblogs.com/tonix/p/4516624.html