HouseRobber

//
// Created by Administrator on 2021/7/27.
//

#ifndef C__TEST01_HOUSEROBBER_HPP
#define C__TEST01_HOUSEROBBER_HPP

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

class HouseRobber {
/* 有一排N栋房子(0 - N-1),房子i里有A[i]个金币
 * 一个窃贼想选择一些房子偷金币
 * 但是不能偷任何挨着的两家邻居,否则会被警察逮住
 * 最多偷多少金币
 * 例子:
 * 输入:A = {3, 8, 4}
 * 输出:8(只偷第二家的金币)
 * */
public:
    HouseRobber(vector<int> An);
    int HouseRobberDP(vector<int> &A);
private:
    vector<int> A;
};

HouseRobber::HouseRobber(vector<int> An):
A(An){
    A.resize(An.size());
}
int HouseRobber::HouseRobberDP(vector<int> &A) {
    if(A.empty()) {
        return 0;
    }
    int N = A.size();

    vector<int> f(N+1);
    f[0] = 0;
    for(int i = 1; i < N+1; ++i){
        f[i] = f[i-1];
        if(i > 1) {
            f[i] = max(f[i - 2] + A[i - 1], f[i - 1]);
        }
    }
    return f[N];
}
#endif //C__TEST01_HOUSEROBBER_HPP

posted @ 2021-07-27 19:09  蘑菇王国大聪明  阅读(23)  评论(0编辑  收藏  举报