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;
}