Leetcode:198. House Robber(week 9)

Description:

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.

解題思路:

題意爲給定一個數組,數組的每個位置表示一個房子,數組的值爲錢的數量,相鄰的數不能同時獲得,否則會驚動警察,其本質就是在一列數組中取出一個或多個不相鄰數,使其和最大。 這是一道動態規劃問題。 可以採用動態規劃的方法實現。我採用的算法是遍歷一遍,然後遍歷的同時將不相鄰的數加起來取最大值,時間複雜度爲O(1),代碼如下:

class Solution {
public:
    int rob(vector<int>& nums) {
        int a = 0, b = 0;
        for (int i = 0; i < nums.size();i++) {
            if (i%2== 0) {
                if (a+ nums[i] > b) {
                    a = a + nums[i];
                } else {
                    a = b;
                }
            } else {
                if (b+ nums[i] > a) {
                    b = b + nums[i];
                } else {
                    b = a;
                }
            }
        }
        if (a > b) return a;
        else return b;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章