動的計画leetcodeでのHouse Robber問題の解決

3252 ワード

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.

つまり、各配列の要素はこの部屋の金額を表していますが、2つの隣接する2つの部屋は同時に強盗することはできません.問題は強盗が最大いくら強盗できるかということです.
配列が1,3,5,7,9であれば、最初の部屋は1百万、2番目の部屋は300万です.の
ダイナミックプランニングの考え方は,大きな問題を小さな問題に分解し,中間計算の値を保存することである.このように演算の複雑さを減らす.
まず2つの変数preを定義します.one:配列中の現在値が存在する位置の前半のシーケンスを表す最適解pre_two:配列中の現在値が存在する位置を表す前の値の前半のシーケンスの最適解
例えば泥棒は今700万の部屋に行って、彼はすでに1、3、5のこの3つの部屋の最良の解を知っていて、つまりpre_one. 1,3この二つの部屋の最適解、つまりpre_two.
果たしてこの700万の部屋を強奪するのだろうか.2つの選択肢があります.
  • この部屋を強奪すると、前の部屋は強奪できません.pre_twoが役に立ちました.
  • この部屋を強盗しなければpre_oneは役に立ちました.最終的な決定の根拠は、この2つの選択のどちらが大きいか、どちらが小さいかを判断することだ.

  • コードは次のとおりです.
    class Solution {
    public:
        int rob(vector<int>& nums) {
            //               
            int pre_one = 0;
            //                    
            int pre_two = 0;
            //               
            int rob = 0;
            int len = nums.size();
            for(int i=0; ireturn rob;   
        }
    };