1. 程式人生 > >House Robber 打家劫舍

House Robber 打家劫舍

//

//  main.cpp

//  robber

//

//  Created by dongfucai on 2018/9/28.

//  Copyright © 2018年 dongfucai. All rights reserved.

//

 

#include <iostream>

#include "vector"

 

using namespace std;

 

/*

 

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to 

@ts for adding additional test cases.

 這道題的本質相當於在一列陣列中取出一個或多個不相鄰數,使其和最大。

 

 我們先拿一個簡單的例子來分析一下,比如說nums為{3, 2, 1, 5},那麼我們來看我們的dp陣列應該是什麼樣的,首先dp[0]=3沒啥疑問,再看dp[1]是多少呢,由於3比2大,所以我們搶第一個房子的3,當前房子的2不搶,所以dp[1]=3,那麼再來看dp[2],由於不能搶相鄰的,所以我們可以用再前面的一個的dp值加上當前的房間值,和當前房間的前面一個dp值比較,取較大值當做當前dp值,所以我們可以得到狀態轉移方程dp[i] = max(num[i] + dp[i - 2], dp[i - 1]), 由此看出我們需要初始化dp[0]和dp[1],其中dp[0]即為num[0],dp[1]此時應該為max(num[0], num[1]),程式碼如下:

 */

class Solution{

    

    public :

    int rob(vector<int> &nums){

        if (nums.size() <= 1) {

            return nums.empty() ? 0 : nums[0];

        }

        vector<int> dp = {nums[0], max(nums[0], nums[1])};

        for (int i = 2; i < nums.size(); ++i) {

            dp.push_back(max(dp[i-1], dp[i-2] + nums[i]));

        }

        return dp.back();

    }

    

};

 

int main(int argc, const char * argv[]) {

    // insert code here...

 

    int temp[] = {4, 5, 6, 6, 2, 5};

    shared_ptr<Solution> solution(new Solution);

    //Solution s = new Solution;

    vector<int> ivec(temp, temp + 6);

    cout << solution->rob(ivec) << endl;

    

 

    std::cout << "Hello, World!\n";

    return 0;

}