1. 程式人生 > >[leetcode]解決House Robber的一點小心得

[leetcode]解決House Robber的一點小心得

本次選擇的題目是

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.

Solution:
這道題的本質相當於在一列陣列中取出一個或多個不相鄰數,使其和最大。那麼我們對於這類求極值的問題首先考慮動態規劃Dynamic Programming來解,我們維護一個一位陣列dp,其中dp[i]表示到i位置時不相鄰數能形成的最大和,那麼遞推公式怎麼寫呢,我們先拿一個簡單的例子來分析一下,比如說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;
        dp.push_back(nums[0]);
        if(nums[1] > nums[0]){
            dp.push_back(nums[1]);
        }
        else{
            dp.push_back(nums[0
]); } for(int i = 2; i < nums.size(); i++){ if((nums[i] + dp[i-2]) > dp[i-1]){ dp.push_back(nums[i] + dp[i-2]); } else{ dp.push_back(dp[i-1]); } } return dp[nums.size()-1]; } };